python监控键盘输入实例代码

yipeiwu_com6年前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创建一个元素都为0的列表实例

实现创建一个元素都为0的列表: l=10 lis=[0]*l lis 输出结果: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 以上这篇Python创建一个元...

Python中with及contextlib的用法详解

Python中with及contextlib的用法详解

本文实例讲述了Python中with及contextlib的用法。分享给大家供大家参考,具体如下: 平常Coding过程中,经常使用到的with场景是(打开文件进行文件处理,然后隐式地执...

简单介绍python封装的基本知识

简单介绍python封装的基本知识

python封装简介 1.效果图:   对比一:   对比二: 2.学习来源代码: # 封装是面向对象的三大特性之一 # 封装指的是隐藏对象中一些不希望被外部所访问到的属性或方...

关于Python数据结构中字典的心得

关于Python数据结构中字典的心得

本篇主要介绍:常见的字典方法、如何处理查不到的键、标准库中 dict 类型的变种、散列表的工作原理等。一下是全部内容: 泛映射类型 collections.abc 模块中有 Mappin...

Pytorch抽取网络层的Feature Map(Vgg)实例

这边我是需要得到图片在Vgg的5个block里relu后的Feature Map (其余网络只需要替换就可以了) 索引可以这样获得 vgg = models.vgg19(pretra...