python keyboard event capturer

865 ワード

import  os
import  sys
import  tty, termios
import time

def keyboardLoop():
    print "Reading from keyboard"
    print "Use WASD keys to control the robot"
    print "Press Caps to move faster"
    print "Press q to quit"
 
    #      
    # while not rospy.is_shutdown():
    while True:
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
		#       
        old_settings[3] = old_settings[3] & ~termios.ICANON & ~termios.ECHO
        try :
            tty.setraw( fd )
            ch = sys.stdin.read( 1 )
        finally :
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        
        print "capture the keyboard event: ", ord(ch)
        if ch == 'q':
            exit()

if __name__ == '__main__':
    keyboardLoop()