编辑:下面使用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
慕斯709654
一只斗牛犬
一只甜甜圈
汪汪一只猫
相关分类