On 2015-05-05 15:36, Alan Gauld wrote:
On 05/05/15 22:30, Jim Mooney Py3.4.3winXP wrote:
Can python detect a keypress?

The following works for my (on my Ubuntu platform) system
although probably won't be of much use on a Redmond OS.

#!/usr/bin/env python3
# file: 'readchar.py'
"""
Provides readchar()
Implementation of a way to get a single character of input
without waiting for the user to hit <Enter>.
(OS is Linux, Ubuntu 14.04)
"""

import tty, sys, termios

class ReadChar():
    def __enter__(self):
        self.fd = sys.stdin.fileno()
        self.old_settings = termios.tcgetattr(self.fd)
        tty.setraw(sys.stdin.fileno())
        return sys.stdin.read(1)
    def __exit__(self, type, value, traceback):
        termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def readchar():
    with ReadChar() as rc:
        return rc

def testrc():
    print\
    ("Testing ReadChar: enter a character and we'll report what it is.")
    while True:
        char = readchar()
        if ord(char) <= 32:
            print("You entered character with ordinal {}, aka {}."
                        .format(ord(char), repr(char)))
        else:
            print("You entered character '{}'."
                        .format(char))
        if char in "^C^D":
            break

if __name__ == "__main__":
    testrc()

To give credit where credit is due: I seem to remember cobbling this together based on something that was discussed on this mailing list quite some time ago.
i.e. it's not original work:-)


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to