How to create a hotkey to stop the script

Hi,

How to create a python script hotkey? With the function to stop the script, for example.

Regards,
jorge

Try this:

def main():
    # Put your main function here.
    print("Working hard")

try:
    main()
except KeyboardInterrupt:
    pass

then use Ctrl-C to halt the script.

On Windows you might need to use Ctrl-Z Enter instead.

Hi Steven D’Aprano,

Thank you

You’re thinking of signalling EOF in a terminal by typing Ctrl-D in POSIX or Ctrl-Z+Enter in Windows. For KeyboardInterrupt, it’s the same Ctrl-C as in POSIX. However, it’s less reliable in Python on Windows because performing synchronous I/O and various waits on the main thread can’t be interrupted, at least not currently. More could be done to improve the consistency of Ctrl-C handling in POSIX vs Windows – e.g. canceling synchronous I/O and implementing more waits to be Ctrl-C aware.

The OP may want a global hotkey in a graphical desktop environment. A global hotkey doesn’t require the terminal window to have the keyboard focus. There are packages on PyPI that can set global hotkeys for particular platforms such as Windows or Linux X11.

1 Like