Capture keyboardinterrupt in Python without try-except

Alex picture Alex · Nov 17, 2010 · Viewed 106.5k times · Source

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.

Answer

Johan Kotlinski picture Johan Kotlinski · Nov 17, 2010

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()