Class _getch: "" "Gets a single character from standard input. Does not echoes to the screen. "" def __init__ (self): Try:self.impl = _getchwindows () except Importerror:try: Self.impl = _getchmaccarbon () except AttributeError:self.impl = _getchunix () def __ca Ll__ (self): return Self.impl () class _getchunix:def __init__ (self): import TTY, SYS, Termios # import Termios No W or else you'll get the Unix version on the Mac def __call__ (self): import sys, TTY, termios fd = Sys.st Din.fileno () old_settings = termios.tcgetattr (FD) Try:tty.setraw (Sys.stdin.fileno ()) ch = sys.stdin.read (1) finally:termios.tcsetattr (FD, Termios. Tcsadrain, old_settings) return Chclass _getchwindows:def __init__ (self): import msvcrt def __call__ ( Self): Import MSVCRT return Msvcrt.getch () class _getchmaccarbon: "" " A function which returns the current ASCII key, that is, down; If no ASCII key is down, and the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html is very helpful in figuring off how to do this. "" "Def __init__ (self): import Carbon carbon.evt #see If it had this (in Unix, it doesn ' t) def __call_ _ (Self): import Carbon if Carbon.Evt.EventAvail (0x0008) [0]==0: # 0x0008 ' The Keydownmask return ' Else: # # The event contains the following info: # (WHAT,MSG,WHEN,WHERE,MOD) =c Arbon. Evt.getnextevent (0x0008) [1] # # The message (msg) contains the ASCII char which is # EXTR Acted with the 0x000000ff charcodemask; This # number is converted to a ASCII character with Chr () and # returned # ( What,msg,when,where,mod) =carbon.evt.getnextevent (0x0008) [1] Return Chr (MSG & 0X000000FF) If __name__ = = ' __main__ ': # A little test print ' press a key ' Inkey = _getch () import sys for i in xrange (Sys.maxint) : K=inkey () If k<> ': Break print ' You pressed ', K
Learn python-get keyboard events across platforms