getkey
Ulli Horlacher
framstag at rus.uni-stuttgart.de
Sat Jan 16 06:26:00 EST 2016
I have an application which runs on Windows and UNIX where I need to get
one keypress from the user (without ENTER).
Keys which sends escape sequences (e.g. cursor or function keys) should be
ignored.
I have a solution for Windows, but not for UNIX:
The first byte of an escape sequence (example: ^[[21~ for F10) is
recognized, but the trailing bytes then are not discarded by
clear_keyboard_buffer() and get_key() returns the second byte of the
escape sequence.
My code:
try:
import msvcrt
except ImportError:
import tty
import select
import termios
def get_key():
try:
k = msvcrt.getch()
except:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
k = sys.stdin.read(1)
finally:
termios.tcsetattr(fd,termios.TCSADRAIN,old_settings)
if k == '\033':
clear_keyboard_buffer()
return get_key()
else:
return k
def clear_keyboard_buffer():
try:
while msvcrt.kbhit(): msvcrt.getwch()
except:
fd = sys.stdin.fileno()
while len(select.select([fd],[],[],0.0)[0]) > 0: os.read(fd,1)
termios.tcflush(sys.stdin,termios.TCIOFLUSH)
--
Ullrich Horlacher Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlacher at tik.uni-stuttgart.de
Universitaet Stuttgart Tel: ++49-711-68565868
Allmandring 30a Fax: ++49-711-682357
70550 Stuttgart (Germany) WWW: http://www.tik.uni-stuttgart.de/
More information about the Python-list
mailing list