当前位置:主页 > 软件编程 > Python代码 >

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

时间:2021-03-08 11:40:46 | 栏目: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()即可使用

您可能感兴趣的文章:

相关文章