Fix Python – Capture keyboardinterrupt in Python without try-except

Question

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


Answer

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

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