Keypress Input
Grant Edwards
invalid at invalid.invalid
Mon Jun 15 11:22:52 EDT 2015
On 2015-06-15, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> Note that going into raw mode has other implications such as not
> being able to exit your program with ctrl-c or suspend with ctrl-z
> etc. You can explicitly process those kinds of contrl keys with
> something like:
>
> while True:
> key = getch()
> if 1 <= ord(key) <= 26:
> ctrl_key = chr(ord(key) + 64)
> print("ctrl-%c" % ctrl_key)
> if ctrl_key == 'C':
> break
> else:
> print("key: '%c'" % key)
It's probably better (at least on Linux) to just enable handling of
those characters in by setting the ISIG lflag:
def getch():
fd = sys.stdin.fileno()
oldsettings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
# enable handling of ctrl-C, ctrl-Z, etc.
attr = termios.tcgetattr(fd)
attr[3] |= termios.ISIG
termios.tcsetattr(fd,termios.TCSANOW,attr)
c = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
return c
It would be a bit cleaner if the termios module supported the the
cfmakeraw(3) function, then you could do it this way and save a couple
of system calls:
def getch():
fd = sys.stdin.fileno()
oldsettings = termios.tcgetattr(fd)
try:
newsettings = termios.makeraw(oldsettings)
newsettings[3] |= termios.ISIG
termios.tcsetattr(fd,termios.TCSANOW,newsettings)
c = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
return c
[I'm a bit surprised that after all these years using literal integers
to index into the attribute list is the "right" way.]
--
Grant Edwards grant.b.edwards Yow! Well, O.K.
at I'll compromise with my
gmail.com principles because of
EXISTENTIAL DESPAIR!
More information about the Python-list
mailing list