Capture keyboardinterrupt in Python without try-except Capture keyboardinterrupt in Python without try-except python python

Capture keyboardinterrupt in Python without try-except


Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signalimport sysimport timeimport threadingdef signal_handler(signal, frame):    print('You pressed Ctrl+C!')    sys.exit(0)signal.signal(signal.SIGINT, signal_handler)print('Press Ctrl+C')forever = threading.Event()forever.wait()


If all you want is to not show the traceback, make your code like this:

## all your app logic heredef main():   ## whatever your app does.if __name__ == "__main__":   try:      main()   except KeyboardInterrupt:      # do nothing here      pass

(Yes, I know that this doesn't directly answer the question, but it's not really clear why needing a try/except block is objectionable -- maybe this makes it less annoying to the OP)


An alternative to setting your own signal handler is to use a context-manager to catch the exception and ignore it:

>>> class CleanExit(object):...     def __enter__(self):...             return self...     def __exit__(self, exc_type, exc_value, exc_tb):...             if exc_type is KeyboardInterrupt:...                     return True...             return exc_type is None... >>> with CleanExit():...     input()    #just to test it... >>>

This removes the try-except block while preserving some explicit mention of what is going on.

This also allows you to ignore the interrupt only in some portions of your code without having to set and reset again the signal handlers everytime.