The examples in this article describe how Python can get keys on a cross-platform implementation. Share to everyone for your reference. Specific as follows:
Copy the Code code as follows:
Class _getch:
"" "Gets a single character from the 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 __call__ (self): return Self.impl ()
Class _getchunix:
def __init__ (self):
Import TTY, SYS, Termios # import Termios now or else you'll get the Unix version on the MAC
def __call__ (self):
Import sys, TTY, Termios
FD = Sys.stdin.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 CH
Class _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 was
Very helpful in figuring off how to does this.
"""
def __init__ (self):
Import Carbon
Carbon.evt #see If it has this (in Unix, it doesn ' t)
def __call__ (self):
Import Carbon
If Carbon.Evt.EventAvail (0x0008) [0]==0: # 0x0008 is the Keydownmask
Return '
Else
#
# The event contains the following info:
# (What,msg,when,where,mod) =carbon.evt.getnextevent (0x0008) [1]
#
# The message (msg) contains the ASCII char which is
# extracted 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
Hopefully this article will help you with Python programming.