我用 pynput 设置了热键:
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<alt>+b'),
on_activate=on_activate
)
# Function to handle canonical form for key events
def for_canonical(f):
return lambda k: f(hotkey_listener.canonical(k))
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)
) as hotkey_listener:
hotkey_listener.join()
这可行,但每次我需要取消脚本并更新代码时,我都需要重新启动内核。我还希望在“Esc”上有一个关键侦听器,按下“Esc”后,脚本将清除所有侦听器并退出。
我想知道如何以线程安全且不混乱的方式执行此操作?在我的
on_activate
函数中,我有像 time.sleep()
这样的东西,我认为这会让线程变得尴尬。
如果您想要一种使代码简单的方法,除了
keyboard
之外,您还可以使用模块pynput
。我认为使用 keyboard.add_hotkey()
来检测“esc”键的按下是最简单的。主要代码如下:
#code before hotkey_listener.join(), including 'import keyboard'
hotkey_listener.join()
keyboard.add_hotkey('esc', lambda: stop_listener(hotkey_listener)) #add callback function when 'esc' is pressed
这是
stop_listener()
函数的代码:
def stop_listener(listener):
listener.stop() #stop the listener thread