Read one key press.
Fredrik Lundh
fredrik at pythonware.com
Tue Oct 19 03:07:14 EDT 1999
Gerrit Holl <gerrit.holl at pobox.com> wrote:
> 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
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list