[英]How to code a threaded keyboard event listener in Python?
我正在為我的 python 腳本創建一個“終止開關”。 本質上,當我的主腳本循環並執行它時,它在后台監聽特定的按鍵,然后在按下該鍵時完全退出腳本。
我只是將定期密鑰檢查放入主腳本中,但是有很多睡眠和等待,並且坐在那里按住密鑰直到下一次檢查出現並不是很實用。
我知道如何為鍵盤鍵編寫事件偵聽器,我以前從未使用過線程。
我正在使用 pynput 以防萬一可能導致與線程庫不兼容。
任何幫助是極大的贊賞。
keyboard
模塊在單獨的線程中捕獲事件,所以它可能是您正在尋找的。
嘗試這樣的事情:
import keyboard
import time
stop_switch = False
def switch(keyboard_event_info):
global stop_switch
stop_switch = True
keyboard.unhook_all()
print(keyboard_event_info)
def main_function():
global stop_switch
keyboard.on_press_key('enter', switch)
while stop_switch is False:
if stop_switch is False:
print("1")
if stop_switch is False:
time.sleep(0.2)
if stop_switch is False:
print("2")
if stop_switch is False:
time.sleep(0.5)
if stop_switch is False:
print("3")
if stop_switch is False:
time.sleep(1)
stop_switch = False
main_function()
幾乎立即從 time.sleep() 退出的簡單方法,例如 10 秒的睡眠:
def main_function():
global stop_switch
keyboard.on_press_key('enter', switch)
while stop_switch is False:
if stop_switch is False:
print("sleeping for 10 seconds")
for i in range(100):
if stop_switch is False:
time.sleep(0.1)
print("program stopped")
stop_switch = False
但更好的方法是使用threading.Event
。 檢查這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.