[英]Python: Start and stop thread using keyboard presses
我正在研究 Python 3.8,我正在嘗試使用鍵盤快捷鍵打開和關閉線程。
這是我的線程 class:
import keyboard
from threading import Thread
import time
class PrintHi(Thread):
def __init__(self):
Thread.__init__(self)
self.active = False
def run(self):
while True:
if self.active:
print("Hi,", time.time())
time.sleep(1)
它似乎按預期工作,我可以啟動線程,然后根據我是要啟用還是禁用,將“thread.active”更改為 True 或 False。
問題是當我嘗試將它與“鍵盤”模塊一起使用時,它無法按預期工作:
class KeyboardHook(object):
def __init__(self):
self.thread = PrintHi()
self.thread.start()
self.set_keyboard_hotkeys()
def toggle_print(self):
print("Toggle Print")
self.thread.active = not self.thread.active
def set_keyboard_hotkeys(self):
print("Setting hotkeys hooks")
keyboard.add_hotkey('ctrl+c', self.toggle_print)
keyboard.wait()
if __name__ == '__main__':
hook = KeyboardHook()
這些是步驟:
線程本身工作正常,鍵盤掛鈎本身也工作正常,但是當我將兩者結合起來時,它們不起作用。
有誰知道我做錯了什么? 有沒有使用鍵盤快捷鍵打開和關閉線程的方法? 在我的應用程序中,我將有多個線程,我必須獨立地打開和關閉它們。
謝謝!
我建議稍微重構您的代碼,即在打印機線程中使用Event
而不是bool
變量來發出打印操作的信號,並添加允許您在程序退出時停止打印機線程的邏輯:
import time
from threading import Thread, Event
import keyboard
class PrintThread(Thread):
def __init__(self):
super().__init__()
self.stop = False
self.print = Event()
def run(self):
while not self.stop:
if self.print.wait(1):
print('Hi,', time.time())
def join(self, timeout=None):
self.stop = True
super().join(timeout)
另外,我建議將阻塞代碼從KeyboadHook
初始化程序移出到單獨的start
方法:
class KeyboardHook:
def __init__(self):
self.printer = PrintThread()
self.set_keyboard_hotkeys()
def toggle_print(self):
print('Toggle the printer thread...')
if self.printer.print.is_set():
self.printer.print.clear()
else:
self.printer.print.set()
def set_keyboard_hotkeys(self):
print('Setting keyboard hotkeys...')
keyboard.add_hotkey('ctrl+p', self.toggle_print)
def start(self):
self.printer.start()
try:
keyboard.wait()
except KeyboardInterrupt:
pass
finally:
self.printer.join()
像這樣運行它:
hook = KeyboardHook()
hook.start()
這段代碼對我來說就像一個魅力。
KeyboardHook 中的一些更改使其運行:
class KeyboardHook(object):
def __init__(self):
self.thread = PrintHi()
self.set_keyboard_hotkeys()
self.thread.start()
def toggle_print(self):
print("Toggle Print")
self.thread.active = not self.thread.active
def set_keyboard_hotkeys(self):
print("Setting hotkeys hooks")
keyboard.add_hotkey('ctrl+p', self.toggle_print)
#keyboard.wait()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.