Fix Python – Capture keyboardinterrupt in Python without try-except


Asked By – Alex

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

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

Now we will see solution for issue: 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 signal
import sys
import time
import threading

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

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()

This question is answered By – Johan Kotlinski

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0