检测python(Redhat / Amazon Linux)中的按键,每次迭代都可能需要几秒钟的时间?

问题描述 投票:1回答:2

我已使用此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

Edit:以下使用keyboard.on_press(callback,抑制= False)的答案在ubuntu中工作正常,没有任何问题。但是在Redhat和Amazon Linux中,甚至没有检测到按键]

python time redhat keypress exit
2个回答
3
投票

您可以在keyboard模块中使用事件处理程序来获得所需的结果。

这样的处理程序是keyboard.on_press(callback, suppress=False)


-1
投票

您可以使用线程

© www.soinside.com 2019 - 2024. All rights reserved.