我已使用此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中,甚至没有检测到按键]
您可以在keyboard
模块中使用事件处理程序来获得所需的结果。
这样的处理程序是keyboard.on_press(callback, suppress=False)
您可以使用线程