python監控鍵盤輸入執行個體代碼,python監控鍵盤輸入
本文研究的主要是python監控鍵盤輸入的相關代碼,用到了os,sys,time等,具體實現代碼如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import tty, termios import time if __name__ == '__main__': print "Reading form keybord" print """ i j k l m""" print 'press Q to quit' 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 'error' if ch=='i': print 'move forward' elif ch=='m': print 'move back' elif ch=='j': print "turn left!" elif ch=='l': print "turn right!" elif ch=='u': print "turn right!" elif ch=='o': print "turn right!" elif ch=='k': print "stop motor!" elif ch=='q': print "shutdown!" break elif ord(ch)==0x3: #這個是ctrl c print "shutdown" break print "Reading form keybord" print """ i j k l m""" print 'press Q or ctrl+c to quit' #rate.sleep()
結果:
總結
以上就是本文關於python監控鍵盤輸入執行個體代碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!