signals - Python: Catch Ctrl-C command. Prompt "really want to quit (y/n)", resume execution if no -
i have program may have lengthy execution. in main module have following:
import signal def run_program() ...time consuming execution... def exit_gracefully(signal, frame): ... log exiting information ... ... close open files ... sys.exit(0) if __name__ == '__main__': signal.signal(signal.sigint, exit_gracefully) run_program()
this works fine, i'd possibility pause execution upon catching sigint, prompting user if quit, , resuming left off in run_program() if decide don't want quit.
the way can think of doing running program in separate thread, keeping main thread waiting on , ready catch sigint. if user wants quit main thread can cleanup , kill child thread.
is there simpler way?
the python signal handlers not seem real signal handlers; happen after fact, in normal flow , after c handler has returned. you'd try put quit logic within signal handler. signal handler runs in main thread, block execution there too.
something seems work nicely.
import signal import time import sys def run_program(): while true: time.sleep(1) print("a") def exit_gracefully(signum, frame): # restore original signal handler otherwise evil things happen # in raw_input when ctrl+c pressed, , our signal handler not re-entrant signal.signal(signal.sigint, original_sigint) try: if raw_input("\nreally quit? (y/n)> ").lower().startswith('y'): sys.exit(1) except keyboardinterrupt: print("ok ok, quitting") sys.exit(1) # restore exit gracefully handler here signal.signal(signal.sigint, exit_gracefully) if __name__ == '__main__': # store original sigint handler original_sigint = signal.getsignal(signal.sigint) signal.signal(signal.sigint, exit_gracefully) run_program()
the code restores original signal handler duration of raw_input
; raw_input
not re-entrable, , re-entering lead runtimeerror: can't re-enter readline
being raised time.sleep
don't want harder catch keyboardinterrupt
. rather, let 2 consecutive ctrl-c's raise keyboardinterrupt
.
Comments
Post a Comment