When I press Ctrl-C, the following code terminates immediately.
However, it seems that the loop should exit after a 10 second delay – because it is not checking the status of keep_going until we reach the top of the loop. Why is this code exiting the loop immediately?
How would I make sure that the loop finishes execution before exiting?
import signal
import time
keep_going = True
def signal_handler(signal, frame):
global keep_going
print 'quitting!'
keep_going = False
signal.signal(signal.SIGINT, signal_handler)
while keep_going:
print 'looping...'
time.sleep(10)
print 'bye!'
From Python docs:
I.e. the loop does finish its execution (as you can see from the
"bye"being output after the signal handler’s"quitting!"), it’s justsleepthat is cut short.If you had something more substantial than
sleep, I believe you’d see what you originally wanted.