Python installs its own SIGINT
handler in order to raise KeyboardInterrupt
exceptions. Setting the signal to SIG_DFL
will not restore that handler, but the "standard" handler of the system itself (which terminates the interpreter).
You have to store the original handler and restore that handler when you're done:
original_sigint_handler = signal.getsignal(signal.SIGINT)
# Then, later...
signal.signal(signal.SIGINT, original_sigint_handler)
As kindall rightfully says in comments, you can express this as a context manager:
from contextlib import contextmanager
@contextmanager
def sigint_ignored():
original_sigint_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
print('Now ignoring CTRL-C')
yield
except:
raise # Exception is dropped if we don't reraise it.
finally:
print('Returning control to default signal handler')
signal.signal(signal.SIGINT, original_sigint_handler)
You can use it like this:
# marker 1
print('No signal handler modifications yet')
print('Sleeping...')
time.sleep(10)
# marker 2
with sigint_ignored():
print('Sleeping...')
time.sleep(10)
# marker 3
print('Sleeping...')
time.sleep(10)