Entry
Read one key press
Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 301, Fredrik Lundh
"""
Packages: operating_systems.windows;operating_systems.unix
"""
"""
> if I have the following program:
>
> key = raw_input("press a key: ")
> if key == 'a':
> print "you pressed 'a'"
> elif key == '^['
> print "you pressed escape"
>
> it doesn't work. Well, it works but it itsn't what I'm looking for. I want
> ONE key input. Can this me done easyly?
well, at least it can be done in Python. here's something
that appears to work on Windows and Linux (should have
been in the guide, but didn't quite make it).
"""
# tty-example-2.py
import sys
try:
# windows or dos
import msvcrt
getkey = msvcrt.getch
except ImportError:
# assume unix
import tty, termios, TERMIOS
def getkey():
file = sys.stdin.fileno()
mode = termios.tcgetattr(file)
try:
tty.setraw(file, TERMIOS.TCSANOW)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(file, TERMIOS.TCSANOW, mode)
return ch
print "press 'q' to quit..."
while 1:
ch = getkey()
if ch == "q":
break
print ch,
print