簡體   English   中英

Python:使用鍵盤按鍵啟動和停止線程

[英]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()

這些是步驟:

  • 我首先創建線程,將其存儲在“self.thread”中並啟動它。
  • 然后我設置鍵盤熱鍵掛鈎
  • 當我按 'ctrl+c' 時,'toggle_print()' function 應該執行
  • 這應該將線程的 active 屬性設置為 True 從而啟用打印。

線程本身工作正常,鍵盤掛鈎本身也工作正常,但是當我將兩者結合起來時,它們不起作用。

有誰知道我做錯了什么? 有沒有使用鍵盤快捷鍵打開和關閉線程的方法? 在我的應用程序中,我將有多個線程,我必須獨立地打開和關閉它們。

謝謝!

我建議稍微重構您的代碼,即在打印機線程中使用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 中的一些更改使其運行:

  1. 你不需要keyboard.wait()
  2. 設置熱鍵后啟動線程
  3. 最好將熱鍵從 ctrl-c 更改為其他內容
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM