Python下非阻塞式读取键盘输入

Python下非阻塞式读取键盘输入

在Python编程中,有时需要实时地读取键盘输入,但是正常的输入方式会阻塞程序执行,导致不能及时响应。这时可以使用一些技巧实现非阻塞式获取键盘输入。

本文将介绍在Python中如何通过ttytermios模块实现非阻塞读取键盘输入。主要分为以下几个步骤:

导入模块

导入所需的模块,包括ttytermiosselect

  • tty模块可以设置终端模式
  • termios可以保存和恢复终端属性
  • select实现输入监听
import tty
import termios
import select

设置终端为原始模式

调用tty.setraw()将终端设置为原始模式,这样就可以不用按回车,直接读取键盘输入。

tty.setraw(sys.stdin.fileno())

监听输入

使用select.select()来监听标准输入stdin,并设置超时时间,例如0.1秒。

rlist, _, _ = select.select([sys.stdin], [], [], 0.1)

读取输入

在超时时间内如果有键盘输入,则读取一个字符并保存到变量key中;如果超时没有输入,key设置为空字符串。

if rlist:
    key = sys.stdin.read(1)
else:
    key = ''

恢复终端属性

最后使用termios.tcsetattr()将终端设置恢复原先的属性,避免影响后续的输入输出。

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)

返回结果

返回key变量,调用函数的地方就可以得到键盘输入或者超时的提示。

通过上述步骤,就可以定期检查键盘输入,如果有输入则返回,没有则不会阻塞程序执行。这样我们可以方便地实现游戏、控制界面等对键盘输入有实时响应需求的应用。

总之,使用ttytermiosselect模块可以在Python中轻松实现非阻塞式读取键盘输入,构建出实时响应的交互程序。

全部代码

import tty #导入tty模块,用于设置终端模式
import sys #导入系统模块
import termios #导入termios模块,用于保存和恢复终端属性
import select #导入select模块,用于实现输入监听

settings = termios.tcgetattr(sys.stdin) #获取标准输入终端属性

def getKey():
    
    tty.setraw(sys.stdin.fileno()) #设置终端为原始模式
    
    rlist, _, _ = select.select([sys.stdin], [], [], 0.1) 
    #监听标准输入,超时0.1秒  
    
    if rlist: #若监听到输入
        
        key = sys.stdin.read(1) 
        #读取一个字符
        
    else:
        
        key = '' #否则设置为空字符
        
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) 
    #恢复标准输入终端属性
    
    return key #返回键盘输入内容

键盘控制小车

代码

#!/usr/bin/env python

# Copyright (c) 2011, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of the Willow Garage, Inc. nor the names of its
#      contributors may be used to endorse or promote products derived from
#       this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import rospy

from geometry_msgs.msg import Twist

import sys, select, termios, tty

msg = """
Control Your Turtlebot!
---------------------------
Moving around:
   u    i    o  [ ]
   j    k    l
   m    ,    .

q/z : increase/decrease max speeds by 10%
w/x : increase/decrease only linear speed by 10%
e/c : increase/decrease only angular speed by 10%
space key, k : force stop
anything else : stop smoothly

CTRL-C to quit
"""

moveBindings = {
        'i':(1,0,0),
        'o':(1,-1,0),
        'j':(0,1,0),
        'l':(0,-1,0),
        'u':(1,1,0),
        ',':(-1,0,0),
        '.':(-1,1,0),
        'm':(-1,-1,0),
        '[':(0,0,1),
        ']':(0,0,-1),
           }

speedBindings={
        'q':(1.1,1.1),
        'z':(.9,.9),
        'w':(1.1,1),
        'x':(.9,1),
        'e':(1,1.1),
        'c':(1,.9),
          }

def getKey():
    tty.setraw(sys.stdin.fileno())
    rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
    if rlist:
        key = sys.stdin.read(1)
    else:
        key = ''

    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
    return key

speed = .2
speed_y = .2
turn = 1

def vels(speed,turn):
    return "currently:\tspeed %s\tturn %s " % (speed,turn)

if __name__=="__main__":
    settings = termios.tcgetattr(sys.stdin)

    rospy.init_node('robint_teleop')
    pub = rospy.Publisher('/cmd_vel/joy_pub', Twist, queue_size=1)
    # pub_gazebo = rospy.Publisher('cmd_vel', Twist, queue_size=5)
    rate = rospy.Rate(50) # 10hz

    x = 0
    y = 0
    th = 0
    status = 0
    count = 0
    acc = 0.1
    target_speed = 0
    target_speed_y = 0
    target_turn = 0
    control_speed = 0
    control_speed_y = 0
    control_turn = 0
    try:
        print(msg)
        print(vels(speed,turn))
        while(1):
            key = getKey()
            if key in moveBindings.keys():
                x = moveBindings[key][0]
                y = moveBindings[key][2]
                th = moveBindings[key][1]
                count = 0
            elif key in speedBindings.keys():
                speed = speed * speedBindings[key][0]
                speed_y = speed_y * speedBindings[key][0]
                turn = turn * speedBindings[key][1]
                count = 0

                print(vels(speed,turn))
                if (status == 14):
                    print(msg)
                status = (status + 1) % 15
            elif key == ' ' or key == 'k' :
                x = 0
                y = 0
                th = 0
                control_speed = 0
                control_speed_y = 0
                control_turn = 0
            else:
                count = count + 1
                if count > 4:
                    x = 0
                    y = 0
                    th = 0
                if (key == '\x03'):
                    break

            target_speed = speed * x
            target_speed_y = speed_y * y
            target_turn = turn * th

            if target_speed > control_speed:
                control_speed = min( target_speed, control_speed + 0.02 )
            elif target_speed < control_speed:
                control_speed = max( target_speed, control_speed - 0.02 )
            else:
                control_speed = target_speed

            if target_speed_y > control_speed_y:
                control_speed_y = min( target_speed_y, control_speed_y + 0.02 )
            elif target_speed_y < control_speed_y:
                control_speed_y = max( target_speed_y, control_speed_y - 0.02 )
            else:
                control_speed_y = target_speed_y

            if target_turn > control_turn:
                control_turn = min( target_turn, control_turn + 0.1 )
            elif target_turn < control_turn:
                control_turn = max( target_turn, control_turn - 0.1 )
            else:
                control_turn = target_turn

            twist = Twist()
            twist.linear.x = control_speed; twist.linear.y = control_speed_y; twist.linear.z = 0
            twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = control_turn
            pub.publish(twist)
            # rate.sleep()
            # pub_gazebo.publish(twist)

            #print("loop: {0}".format(count))
            #print("target: vx: {0}, wz: {1}".format(target_speed, target_turn))
            #print("publihsed: vx: {0}, wz: {1}".format(twist.linear.x, twist.angular.z))

    except Exception as e:
        print(e)

    finally:
        twist = Twist()
        twist.linear.x = 0; twist.linear.y = 0; twist.linear.z = 0
        twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0
        pub.publish(twist)
        # pub_gazebo.publish(twist)

    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)


  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值