Register your handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal can be found here.
Python
docs.python.org โบ 3 โบ library โบ signal.html
signal โ Set handlers for asynchronous events
The signal.signal() function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python ...
Top answer 1 of 13
1087
Register your handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal can be found here.
2 of 13
223
You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:
import time, sys
x = 1
while True:
try:
print x
time.sleep(.3)
x += 1
except KeyboardInterrupt:
print "Bye"
sys.exit()
Videos
Tutorialspoint
tutorialspoint.com โบ python โบ python_signal_handling.htm
Python - Signal Handling
A signal handler is a function that gets executed when a specific signal is received. The signal.signal() function allows defining custom handlers for signals. The signal module offers a way to define custom handlers that will be executed when ...
University of New Brunswick
cs.unb.ca โบ ~bremner โบ teaching โบ cs2613 โบ books โบ python3-doc โบ library โบ signal.html
signal โ Set handlers for asynchronous events โ Python 3.9.2 documentation
The signal.signal() function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a ...
W3Schools
w3schools.com โบ python โบ ref_module_signal.asp
Python signal Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... import signal import sys def handler(signum, frame): print('Signal received, exiting gracefully...') sys.exit(0) signal.signal(signal.SIGINT, handler) print('Press Ctrl+C to trigger signal') Try it Yourself ยป
The Ramblings
anonbadger.wordpress.com โบ 2018 โบ 12 โบ 15 โบ python-signal-handlers-and-exceptions
Python, signal handlers, and exceptions โ The Ramblings
December 19, 2018 - If you search the internet for how to implement a timeout in Python, youโll find tons of examples using signals, including one from the standard library documentation and one which is probably where the design for our original decorator came from. So letโs create some quick test code to show how the signal works to implement a timeout ยท import signal import time def handler(signum, frame): print('Signal handler called with signal', signum) raise OSError("timeout exceeded!") def long_function(): time.sleep(10) # Set the signal handler and a 1-second alarm old_handler = signal.signal(signal.SIGALRM, handler) signal.alarm(1) # This sleeps for longer than the alarm start = time.time() try: long_function() except OSError as e: duration = time.time() - start print('Duration: %.2f' % duration) raise finally: signal.signal(signal.SIGALRM, old_handler) signal.alarm(0) # Disable the alarm
Marco
marco.ninja โบ blog โบ notes โบ technology โบ python โบ python-handling-signals
Handling signals with Python | marco.ninja
October 25, 2025 - import time TOTAL_SLEEP = 60 print("Starting program") signal_handler = SignalHandler() while not signal_handler.stop: do_something() # Instead of time.sleep(TOTAL_SLEEP) for _ in range(0, TOTAL_SLEEP): time.sleep(1) if signal_handler.stop: break print("Saving state and stopping gracefully")
David Hamann
davidhamann.de โบ posts โบ handling and confirming (interrupt) signals in python
Handling and confirming (interrupt) signals in Python | David Hamann
September 29, 2022 - Once set, we overwrite the default behavior and wonโt get any KeyboardInterrupts anymore (although you could easily recreate the default behavior by setting the previous handler again, which is returned by signal()). Running the program and then sending an interrupt (<Control-c>) will now look something like this: $ python3 demo.py .....^CHandling signal 2 (SIGINT).
Python
docs.python.org โบ 3.9 โบ library โบ signal.html
signal โ Set handlers for asynchronous events โ Python 3.9.24 documentation
A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for SIGCHLD, which follows the underlying implementation.
Python
docs.python.org โบ 3.10 โบ library โบ signal.html
signal โ Set handlers for asynchronous events โ Python 3.10.16 documentation
A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for SIGCHLD, which follows the underlying implementation.
GitHub
github.com โบ xanthium-enterprises โบ OS-Signal-Handling-in-Python
GitHub - xanthium-enterprises/OS-Signal-Handling-in-Python: Basic Signal Handling in Python
How to use and customize operating system signals like SIGINT and SIGBREAK to control the flow of your python script during execution.
Starred by 6 users
Forked by 3 users
Languages ย Python 99.6% | Batchfile 0.4% | Python 99.6% | Batchfile 0.4%
Xanthium
xanthium.in โบ operating-system-signal-handling-in-python3
Capturing and Handling OS signals like SIGINT (CTRL-C) in Python | xanthium enterprises
October 18, 2023 - The receiving Program can either execute the default function specified by the SIGINT signal or It can use a signal handler to trap the SIGINT signal and execute a custom user specified function. Not all signals are available on all systems. Signals differ between operating systems(Linux/Windows) Since not all signals are available in every OS, It is good to know which ones are available on your system. Here we will be using Python 3 (Python 3.9.x) and to access the OS signals we have to import the signal module
Python Module of the Week
pymotw.com โบ 2 โบ signal
signal โ Receive notification of asynchronous system events - Python Module of the Week
When the signal handler returns, the loop continues. To send signals to the running program, I use the command line program kill. To produce the output below, I ran signal_signal.py in one window, then kill -USR1 $pid, kill -USR2 $pid, and kill -INT $pid in another. $ python signal_signal.py My PID is: 71387 Waiting...