简体   繁体   中英

How to code a threaded keyboard event listener in Python?

I'm looking to make a 'kill switch' for my python script. Essentially, while my main script is looping and doing it's thing, in the background it's listening for a specific key press and then exits the script entirely when that key is pressed.

I would just throw periodic key checks into the main script, however there are many sleeps and waits, and sitting there holding down the key until the next check comes up isn't very practical.

I know how to code the event listener for the keyboard key, I've just never worked with threads before.

I am using pynput just in case that might cause any incompatibilities with threading libraries.

Any help is greatly appreciated.

keyboard module is capturing events in separate thread, so it might be what you are looking for.

Try something like this:

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()

Simple way to exit almost immediately from time.sleep() with for example 10 seconds of sleep:

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

But better approach is to use threading.Event . Check this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM