self.old_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, self.handler)

def handler(self, sig, frame):
    self.signal_received = sig, frame
logging.debug('SIGINT received. Delaying KeyboardInterrupt.')

def __exit__(self, type, value, traceback):
    signal.signal(signal.SIGINT, self.old_handler)
if self.signal_received:
    self.old_handler(*self.signal_received)
with DelayedKeyboardInterrupt():
    critical_code()
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?