pythontry-catchkeyboardinterrupt

Capture keyboardinterrupt in Python without try-except


Is there some way in Python to capture KeyboardInterrupt event without putting all the code inside a try-except statement?

I want to cleanly exit without trace if user presses Ctrl+C.


Solution

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

    import signal
    import sys
    import time
    import threading
    
    def 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()