1

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.

1 Answers1

1

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.

Dawid Rutkowski
  • 410
  • 3
  • 8
  • This is a great answer, and definitely works in terms of the background listener, so thank you. However I do have another issue. As it stands, if I were to have a 20 second sleep for example, when I hit the key to kill the script, it still waits to finish that 20 second sleep before terminating. I've tried using sys.exit() as well, but it still waits for current commands to finish running before exiting. Do you know of a way to just immediately kill all threads? – Keegan Heffernan Apr 15 '20 at 19:35