Python Signal Handling — ELI5
Imagine you’re wearing headphones and drawing. Your mom wants your attention. She can’t just change your drawing — she taps you on the shoulder. You take off the headphones and ask “what’s up?”
That shoulder tap is a signal.
Your computer’s operating system (like Windows or Linux) uses signals to talk to running programs. The most common one is the “please stop” signal — when you press Ctrl+C in a terminal, you’re sending a signal that means “I want this program to stop.”
By default, Python programs just crash when they get that signal. But you can teach your program to handle it politely. Instead of crashing, it can save its work first, close files it was writing to, and then exit cleanly. Like putting your pencils away before leaving the table.
There are different kinds of taps:
- SIGINT (Ctrl+C): “Please stop when you can”
- SIGTERM: “Finish up and exit” (this is how servers get told to shut down)
- SIGALRM: “Your timer went off” (like an alarm clock for your program)
Some signals are forceful — SIGKILL just yanks you out of the chair. Your program can’t catch or ignore it. The OS has the final say.
Signal handling is mostly useful for long-running programs — servers, background workers, scripts that process huge files. Short scripts that run and finish usually don’t need it.
One thing to remember: Signals are the operating system’s way of poking your program — Python lets you decide how to respond instead of just crashing.
See Also
- Python Select And Polling How Python watches many connections at once without wasting energy — like a lifeguard scanning an entire pool.
- Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
- Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.
- Python 310 New Features Python 3.10 gave programmers a shape-sorting machine, friendlier error messages, and cleaner ways to say 'this or that' in type hints.
- Python 311 New Features Python 3.11 made everything faster, error messages smarter, and let you catch several mistakes at once instead of stopping at the first one.