Handling and confirming (interrupt) signals in Python
Let’s say you have a long-running Python script that should run uninterrupted or perform a graceful shutdown should a user decide to terminate it ahead of completion. By default, sending an interrupt (usually by pressing <Control-C>) to a running Python program will raise a KeyboardInterrupt exception. One way of (gracefully or not) handling interrupts is to catch this specific exception. For example like this: while True: try: do_your_thing() except KeyboardInterrupt: clean_up() sys.exit(0) This generally works fine. However, you can still trigger another KeyboardInterrupt while the clean_up is running and thus interrupt the clean-up process. Also, as interrupts might be sent accidentally (ever cancelled the wrong script because you thought you were in a different pane?), it would be nice to let the user confirm that the script should indeed be interrupted. ...