Best way to close the program pressing Esc anytime the user wants?

Viewed 252

Which is the best way to close a program anytime by pressing Esc? I need to implement this thing in an important code, but my experiments didn't work.

This is the last one:

from multiprocessing import Process
import keyboard
import sys


def stop_anytime():
    bool = True
    while bool:
        try:
            if keyboard.is_pressed('Esc'):
                sys.exit()
                bool = False
        except:
            break

def print_numbers():
    for n in range(150000):
        print(n)
 

if __name__ == '__main__':
    p1 = Process(target=stop_anytime)
    p2 = Process(target=print_numbers)
    p1.start()
    p2.start()
2 Answers

edit: this works:

import keyboard
import sys

def print_numbers():
    for n in range(150000):
        print(n)
        if keyboard.is_pressed('Esc'):
            sys.exit()


if __name__ == '__main__':
    print_numbers()

you have to join the processes like this:

p1.join()
p2.join()

or maybe that has to be done with threading only

also you maybe could do this:

def print_numbers():
    for n in range(150000):
        print(n)
        if keyboard.is_pressed('Esc'):
            sys.exit()

or possibly even use pygame module for the code above to register key presses

The keyboard module is multithreaded, so you don't need to use the multiprocessing module yourself to do this. I think the cleanest way to do things would be to use the keyboard.hook() function to specify a callback function that does what's needed.

Note: Since this callback will be invoked from a separate keyboard thread, calling sys.exit() in it will only exit that, not the whole program/process. To accomplish that you need to call os._exit() instead.

import keyboard
import os


def exit_on_key(keyname):
    """ Create callback function that exits current process when the key with
        the given name is pressed.
    """
    def callback(event):
        if event.name == keyname:
            os._exit(1)
    return callback


def print_numbers():
    for n in range(150000):
        print(n)


if __name__ == '__main__':

    keyboard.hook(exit_on_key('esc'))
    print_numbers()
Related