gpt4 book ai didi

python - 检测python中的按键,每次迭代可能需要几秒钟以上?

转载 作者:行者123 更新时间:2023-12-03 19:16:13 26 4
gpt4 key购买 nike

编辑:以下是使用 的答案keyboard.on_press(回调,抑制=假)在 ubuntu 中运行良好,没有任何问题。
但在 红帽/亚马逊 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 - 检测python中的按键,每次迭代可能需要几秒钟以上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60490193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com