python实时检测键盘输入函数的示例

yipeiwu_com6年前Python基础

在嵌入式、尤其是机器人的python编程中,经常需要实时检测用户的键盘输入来随时控制机器人,这段代码可以帮助我们提取用户输入的字符,并在按下键盘的时候作出反应。

import sys
import tty
import termios

def readchar():
  fd = sys.stdin.fileno()
  old_settings = termios.tcgetattr(fd)
  try:
    tty.setraw(sys.stdin.fileno())
    ch = sys.stdin.read(1)
  finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  return ch

def readkey(getchar_fn=None):
  getchar = getchar_fn or readchar
  c1 = getchar()
  if ord(c1) != 0x1b:
    return c1
  c2 = getchar()
  if ord(c2) != 0x5b:
    return c1
  c3 = getchar()
  return chr(0x10 + ord(c3) - 65)

while True:
  key=readkey()
  if key=='w':
    #go_forward()
  if key=='a':
    #go_back()
  if key=='s':
    #go_left()
  if key=='d':
  	#go_right()
  if key=='q':
  	break

key = readkey()即可使用

以上这篇python实时检测键盘输入函数的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python多进程使用及线程池的使用方法代码详解

多进程:主要运行multiprocessing模块 import os,time import sys from multiprocessing import Process cla...

Empty test suite.(PyCharm程序运行错误的解决方法)

Empty test suite.(PyCharm程序运行错误的解决方法)

运行程序test4_4.py时报错,Empty test suite. 查找资料发现原因: 默认情况下,PyCharm将检查以test开头的文件,它们是unittest.TestCas...

Python命名空间的本质和加载顺序

Python的命名空间是Python程序猿必须了解的内容,对Python命名空间的学习,将使我们在本质上掌握一些Python中的琐碎的规则。 接下来我将分四部分揭示Python命名空间的...

python抽象基类用法实例分析

本文实例讲述了python抽象基类用法。分享给大家供大家参考。具体如下: 定义抽象类,需要使用abc模块,该模块定义了一个元类(ABCMeata),和装饰器 @abstractmetho...

python 捕获shell脚本的输出结果实例

import subprocess output =Popen(["mycmd","myarg"], stdout=PIPE).communicate()[0] import subp...