[Tutor] Single char input

Alex Kleider akleider at sonic.net
Wed Oct 23 19:14:59 EDT 2019


> On 23 October 2019, at 22:25, Ed Connell <edwinconnell at gmail.com> 
> wrote:
> 
>> Hi,
>> How can I accept, evaluate, and act on a single keypress in python?

This question rang bells in my head so I dug around and found something 
I came up with years (>5 to be precise) ago, probably based on help I 
got from this same tutor list so I pass it on with the proviso that Alan 
mentions: it is likely to work only on a Unix system (Linux and probably 
Mac OsX.) I'm running Ubuntu (GNU/Linux.) (On second thought, perhaps it 
could work on a MicroSoft platform since the work is really done by the 
imported modules and presumably they'd be custom for the OS on which 
they are installed.)

import sys
import tty
import 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 ('q' to quit.)")
     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 "qQ":
                 print("..which is the signal to quit testing 
readchar().")
                 break



More information about the Tutor mailing list