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

yipeiwu_com5年前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设计】。

相关文章

Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解

Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解

本文实例讲述了Python3.5变量、数据结构、条件和循环语句、break与continue语句。分享给大家供大家参考,具体如下: 1、变量:即一个容器概念 Python中的变量时一个...

python3 读取Excel表格中的数据

需要先安装openpyxl库 通过pip命令安装: pip install openpyxl 源码如下: #!/usr/bin/python3 #-*- coding:utf-8 -...

在python里从协程返回一个值的示例

下面的例子演法了怎么样从协程里返回一个值: import asyncio async def coroutine(): print('in coroutine') ret...

python获取图片颜色信息的方法

本文实例讲述了python获取图片颜色信息的方法。分享给大家供大家参考。具体分析如下: python的pil模块可以从图片获得图片每个像素点的颜色信息,下面的代码演示了如何获取图片所有点...

pytorch:torch.mm()和torch.matmul()的使用

如下所示: torch.mm(mat1, mat2, out=None) → Tensor torch.matmul(mat1, mat2, out=None) → Tensor...