在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间? [英] detect key press in python, where each iteration can take more than a couple of seconds?

查看:0
本文介绍了在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:以下使用keyboard.on_press(Callback,Suppress=False)的答案在ubuntu中运行正常,没有任何问题。 但在Redhat/Amazon Linux中,它无法工作。

我已经使用了thread

中的代码片段
import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

但上面的代码要求每次迭代在纳秒内执行。在以下情况下失败:

import keyboard  # using module keyboard
import time
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break

推荐答案

您可以在keyboard模块中使用事件处理程序来达到预期效果。

一个这样的处理程序keyboard.on_press(callback, suppress=False): 它为每个key_down事件调用一个回调。 有关详细信息,请访问keyboard docs

以下是您可以尝试的代码:

import keyboard  # using module keyboard
import time

stop = False
def onkeypress(event):
    global stop
    if event.name == 'q':
        stop = True

# ---------> hook event handler
keyboard.on_press(onkeypress)
# --------->

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if stop:  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break

这篇关于在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆