为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨魅力 2022-08-16 10:51:12
编辑:下面使用keyboard.on_press(回调,suppress=False)的答案在ubuntu中工作正常,没有任何问题。但是在Redhat/Amazon linux中,它无法正常工作。我使用了此线程中的代码片段import keyboard  # using module keyboardwhile 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 keyboardimport timewhile 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
查看完整描述

4 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

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


一个这样的处理程序是keyboard.on_press(回调,suppress=False):它为每个事件调用一个回调。您可以在键盘文档中了解更多信息key_down


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


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


查看完整回答
反对 回复 2022-08-16
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

对于将来可能需要它的人,您可以使用它基本上等到按键被按下keyboard.wait()


keyboard.wait("o")

print("you pressed the letter o")

请记住,它会阻止代码执行。如果你想运行代码,如果键没有被按下,我建议做


if keyboard.is_pressed("0"): 

    #do stuff

else: 

    #do other stuff


查看完整回答
反对 回复 2022-08-16
?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

没关系,另一个答案使用几乎相同的方法


这是我可以想到的,使用相同的“键盘”模块,请参阅下面的代码内注释


import keyboard, time

from queue import Queue 


# keyboard keypress callback

def on_keypress(e): 

    keys_queue.put(e.name)


# tell keyboard module to tell us about keypresses via callback

# this callback happens on a separate thread

keys_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()


查看完整回答
反对 回复 2022-08-16
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

您可以使用线程


import threading


class KeyboardEvent(threading.Thread):

    def run(self):

        if keyboard.is_pressed('q'):  # if key 'q' is pressed 

            print('You Pressed A Key!')

            break  # finishing the loop


keyread = KeyboardEvent()

keyread.start()

这将与主线程中的任何内容并行运行,并且专门用于基本上侦听该按键。


查看完整回答
反对 回复 2022-08-16
  • 4 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号