python监控键盘输入实例代码

(编辑:jimmy 日期: 2025/3/13 浏览:2)

本文研究的主要是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监控键盘输入实例代码

总结

以上就是本文关于python监控键盘输入实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。