Showing posts with label console. Show all posts
Showing posts with label console. Show all posts

Monday, June 30, 2008

Get Key Press in Python

Getting single key press without having user pres ENTER.

Windows:


import msvcrt

def getkey():
return msvcrt.getch()


Linux:

import termios, sys, os
TERMIOS = termios

def getkey():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
new[6][TERMIOS.VMIN] = 1
new[6][TERMIOS.VTIME] = 0
termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
c = None
try:
c = os.read(fd, 1)
finally:
termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
return c



Usefull links:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197140