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与mysql数据库交互的实现

python与mysql数据库交互的实现

1、安装pymysql库 如果你想要使用python操作MySQL数据库,就必须先要安装pymysql库,这个库的安装很简单,直接使用pip install pymysql;进行安装。...

解决python中用matplotlib画多幅图时出现图形部分重叠的问题

1.解决方法:使用函数 tight_layout() 2.具体使用方法 import matplotlib.pyplot as plt fig = plt.figure()...

Python中用函数作为返回值和实现闭包的教程

函数作为返回值 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。 我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的: def calc_sum(*ar...

pytorch使用指定GPU训练的实例

本文适合多GPU的机器,并且每个用户需要单独使用GPU训练。 虽然pytorch提供了指定gpu的几种方式,但是使用不当的话会遇到out of memory的问题,主要是因为pytorc...

python字典序问题实例

本文实例讲述了python字典序问题,分享给大家供大家参考。具体如下: 问题描述: 将字母从左向右的次序与字母表中的次序相同,且每个字符最大出现一次..例如:a,b,ab,bc,xyz等...