Read one key press.
Carel Fellinger
cfelling at iae.nl
Mon Oct 18 17:56:23 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?
as you are running linux it sure can be done:) though not as easily as
in Windows. For a better understanding try reading the libc info pages,
menu "Low-Level Terminal Interface". You can find the example I recoded
in python in its submenu "Noncanon Example". Also have a look at the
termios module.
import termios, TERMIOS, sys
fd = sys.stdin.fileno()
def getch():
saved_attributes = termios.tcgetattr(fd)
try:
attributes = termios.tcgetattr(fd) #get a fresh copy!
attributes[3] = attributes[3] & ~(TERMIOS.ICANON | TERMIOS.ECHO)
attributes[6][TERMIOS.VMIN] = 1
attributes[6][TERMIOS.VTIME] = 0
termios.tcsetattr(fd, TERMIOS.TCSANOW, attributes)
a = sys.stdin.read(1)
finally: #be sure to reset the attributes no matter what!
termios.tcsetattr(fd, TERMIOS.TCSANOW, saved_attributes)
return a
--
groetjes, carel
More information about the Python-list
mailing list