Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The python signal handlers do not seem to be real signal handlers; that is they happen after the fact, in the normal flow and after the C handler has already returned. Thus you'd try to put your quit logic within the signal handler. As the signal handler runs in the main thread, it will block execution there too.</p> <p>Something like this seems to work nicely.</p> <pre><code>import signal import time import sys def run_program(): while True: time.sleep(1) print("a") def exit_gracefully(signum, frame): # restore the original signal handler as otherwise evil things will happen # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant signal.signal(signal.SIGINT, original_sigint) try: if raw_input("\nReally quit? (y/n)&gt; ").lower().startswith('y'): sys.exit(1) except KeyboardInterrupt: print("Ok ok, quitting") sys.exit(1) # restore the exit gracefully handler here signal.signal(signal.SIGINT, exit_gracefully) if __name__ == '__main__': # store the original SIGINT handler original_sigint = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, exit_gracefully) run_program() </code></pre> <p>The code restores the original signal handler for the duration of <code>raw_input</code>; <code>raw_input</code> itself is not re-entrable, and re-entering it will lead to <code>RuntimeError: can't re-enter readline</code> being raised from <code>time.sleep</code> which is something we don't want as it is harder to catch than <code>KeyboardInterrupt</code>. Rather, we let 2 consecutive Ctrl-C's to raise <code>KeyboardInterrupt</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload