猿问

在python中检测按键,其中每次迭代可能需要超过几秒钟的时间?

编辑:下面使用keyboard.on_press(回调,suppress=False)的答案在ubuntu中工作正常,没有任何问题。但是在Redhat/Amazon linux中,它无法正常工作。


我使用了此线程中的代码片段


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


杨魅力
浏览 110回答 4
4回答

慕斯709654

您可以使用模块中的事件处理程序来实现所需的结果。keyboard一个这样的处理程序是keyboard.on_press(回调,suppress=False):它为每个事件调用一个回调。您可以在键盘文档中了解更多信息key_down以下是您可以尝试的代码:import keyboard  # using module keyboardimport timestop = Falsedef onkeypress(event):    global stop    if event.name == 'q':        stop = True# ---------> hook event handlerkeyboard.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

一只斗牛犬

对于将来可能需要它的人,您可以使用它基本上等到按键被按下keyboard.wait()keyboard.wait("o")print("you pressed the letter o")请记住,它会阻止代码执行。如果你想运行代码,如果键没有被按下,我建议做if keyboard.is_pressed("0"):     #do stuffelse:     #do other stuff

一只甜甜圈

没关系,另一个答案使用几乎相同的方法这是我可以想到的,使用相同的“键盘”模块,请参阅下面的代码内注释import keyboard, timefrom queue import Queue # keyboard keypress callbackdef on_keypress(e):     keys_queue.put(e.name)# tell keyboard module to tell us about keypresses via callback# this callback happens on a separate threadkeys_queue = Queue() keyboard.on_press(on_keypress)try:    # run the main loop until some key is in the queue    while keys_queue.empty():          print("sleeping")        time.sleep(5)        print("slept")    # check if its the right key    if keys_queue.get()!='q':        raise Exception("terminated by bad key")    # still here? good, this means we've been stoped by the right key    print("terminated by correct key")except:    # well, you can     print("#######")finally:    # stop receiving the callback at this point    keyboard.unhook_all()

汪汪一只猫

您可以使用线程import threadingclass KeyboardEvent(threading.Thread):    def run(self):        if keyboard.is_pressed('q'):  # if key 'q' is pressed             print('You Pressed A Key!')            break  # finishing the loopkeyread = KeyboardEvent()keyread.start()这将与主线程中的任何内容并行运行,并且专门用于基本上侦听该按键。
随时随地看视频慕课网APP

相关分类

Python
我要回答