Alex Alex - 1 month ago 11
Python Question

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.

Answer

Yes, you can install an interrupt handler using the signal module.

import signal
import sys
import time

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C'
while True:
    time.sleep(1)