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编写弹球游戏的实现代码

 弹球游戏: from tkinter import * import time import random tk=Tk() #创建一个界面 tk...

Python构造自定义方法来美化字典结构输出的示例

Python构造自定义方法来美化字典结构输出的示例

示例: 复制代码 代码如下: d = { "root": { "folder2": { "item2": None, "item1": None }, "folder1": { "sub...

在Python中通过getattr获取对象引用的方法

getattr函数 (1)使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 >>> li = ["Larry", "Curly"] >...

Python-opencv 双线性插值实例

我就废话不多说了,直接上代码吧! #coding=utf-8 import cv2 import numpy as np '''双线性插值''' img = cv2.imread('...

pip命令无法使用的解决方法

今天在学习Python时需要安装Requests    使用命令:pip install requests    &...