python监控键盘输入实例代码

yipeiwu_com5年前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监控键盘输入实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python微信撤回监测代码

 本文实例为大家分享了python微信撤回的监测代码,供大家参考,具体内容如下 注意:这里用了一个wechat库,当然,wechat库是基于微信提供的官方接口实现的。 这里的核...

Python 函数返回值的示例代码

0x 00 返回值简介 回顾下,上一节简单介绍了函数及其各种参数,其中也有简单介绍 print 和 return 的区别,print 仅仅是打印在控制台,而 return 则是将 re...

浅析python3中的os.path.dirname(__file__)的使用

Python的3.0版本,常被称为Python 3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0在设计的时候没有考虑...

探究Python中isalnum()方法的使用

 isalnum()方法检查判断字符串是否包含字母数字字符。 语法 以下是isalnum()方法的语法: str.isa1num() 参数  &nbs...

浅谈Python数据类型判断及列表脚本操作

浅谈Python数据类型判断及列表脚本操作

数据类型判断 在python(版本3.0以上)使用变量,并进行值比较时。有时候会出现以下错误: TypeError: unorderable types: NoneType() <...