Notes
| 2023-05-10
(updated 2025-10-25)
| 2 min read
#python
When building a Python script that is long running or has to manage some state on termination it is helpful to handle a couple of signals:
SIGINT: The signal sent when pressing Ctrl+C
SIGTERM and SIGQUIT: Meant to terminate the process, sent by kill and process managers like systemd or supervisord
Handling them is possible with Pythons signals library:
import signals
class SignalHandler:
stop = False
def __init__(self):
# Ctrl+C
signal.signal(signal.SIGINT, self.exit_gracefully)
# Supervisor/process manager signals
signal.signal(signal.SIGTERM, self.exit_gracefully)
signal.signal(signal.SIGQUIT, self.exit_gracefully)
def exit_gracefully(self, *args):
self.stop = True
Example 1: Simple loop
The simplest example is using the SignalHandler as the condition on the loop
and have code to stop gracefully below the loop.
Read more…