signal.
What It Does and Why It Matters
signal.signal(signum, handler) registers a handler for supported process signals. Handler registration generally must occur in the main thread, and supported signals vary across operating systems.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import signal
def handle_interrupt(signal_number, current_frame):
print('Interrupt requested:', signal_number)
previous_handler = signal.getsignal(signal.SIGINT)
try:
signal.signal(signal.SIGINT, handle_interrupt)
print('Handler installed')
finally:
signal.signal(signal.SIGINT, previous_handler)
How the Code Works
- The imports make these standard-library tools available: signal.
- The definition of handle_interrupt creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The name previous_handler receives the value of signal.getsignal(signal.SIGINT). Changing this input lets you explore a different case.
- The structured block controls error handling or resource lifetime, including what happens when an operation fails.
This example depends on operating-system or command-line behavior. Try it in your own terminal after reviewing the relevant permissions and environment assumptions.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
This is useful for scripts, maintenance commands and automated workflows. Treat inputs as untrusted, keep normal results separate from errors, and choose exit codes consistently. Keep reusable logic outside the command-line parser so it can be tested independently.
Practice Exercise
Install and restore a SIGINT handler without sending a real signal.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Attempting to install handlers in worker threads or assuming Unix SIGTERM behavior is identical on every platform.
- Overlooking the documented condition: handler registration generally must occur in the main thread, and supported signals vary across operating systems.
Key Takeaways
- signal.
- signal.signal(signum, handler) registers a handler for supported process signals.
- Install and restore a SIGINT handler without sending a real signal.