pythonprocessmultiprocessingpython-keyboard

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


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

Solution

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