如何在Python中编写线程键盘事件侦听器?

问题描述 投票:0回答:1

我正在为我的python脚本进行“终止开关”操作。本质上,当我的主脚本循环运行时,它在后台监听特定的按键,然后在按下该键时完全退出脚本。

我只是将定期的密钥检查丢入主脚本中,但是有很多睡眠和等待,坐在那里按住密钥直到下一次检查出现是不太实际的。

我知道如何为键盘按键编码事件监听器,我之前从未使用过线程。

我正在使用pynput以防万一可能导致线程库不兼容。

非常感谢您的帮助。

python multithreading background-process event-listener pynput
1个回答
0
投票

[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.Eventthreading.Event

© www.soinside.com 2019 - 2024. All rights reserved.