Catching KeyboardInterrupt in Python during program shutdown Catching KeyboardInterrupt in Python during program shutdown python python

Catching KeyboardInterrupt in Python during program shutdown


Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':    try:        main()    except KeyboardInterrupt:        print('Interrupted')        try:            sys.exit(0)        except SystemExit:            os._exit(0)


You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.