0
0
PythonHow-ToBeginner · 4 min read

How to Use Signal Module in Python: Syntax and Examples

Use the signal module in Python to handle asynchronous events like interrupts by defining a handler function and registering it with signal.signal(). This lets your program respond to signals such as SIGINT (Ctrl+C) gracefully.
📐

Syntax

The signal module lets you catch signals by defining a handler function and registering it with signal.signal(). The handler takes two arguments: the signal number and the current stack frame.

  • signal.signal(signalnum, handler): Registers handler for signalnum.
  • signalnum: The signal you want to catch, like signal.SIGINT.
  • handler: A function that runs when the signal is received.
python
import signal

def handler(signum, frame):
    print(f"Signal handler called with signal: {signum}")

signal.signal(signal.SIGINT, handler)
💻

Example

This example shows how to catch the SIGINT signal (usually sent by pressing Ctrl+C) and run a custom handler instead of immediately stopping the program.

python
import signal
import time

def handler(signum, frame):
    print("Caught SIGINT! Cleaning up before exit.")
    exit(0)

signal.signal(signal.SIGINT, handler)

print("Running. Press Ctrl+C to trigger signal handler.")
while True:
    time.sleep(1)
Output
Running. Press Ctrl+C to trigger signal handler. ^C Caught SIGINT! Cleaning up before exit.
⚠️

Common Pitfalls

Common mistakes when using the signal module include:

  • Trying to use signals on platforms that don't support them well, like Windows (only a few signals like SIGINT work).
  • Using blocking calls inside the signal handler, which can cause unexpected behavior.
  • Not restoring the original signal handler if needed.
  • Assuming signals work in threads other than the main thread (signals are only delivered to the main thread).
python
import signal
import time

def wrong_handler(signum, frame):
    # Blocking call inside handler (bad practice)
    time.sleep(5)
    print("This can cause issues.")

signal.signal(signal.SIGINT, wrong_handler)

print("Try pressing Ctrl+C.")
while True:
    time.sleep(1)
Output
Try pressing Ctrl+C. ^C (This will freeze for 5 seconds before printing message, which is not recommended)
📊

Quick Reference

Function/ConstantDescription
signal.signal(signalnum, handler)Register a handler for a signal
signal.SIGINTInterrupt from keyboard (Ctrl+C)
signal.SIGTERMTermination signal
signal.SIGALRMAlarm clock signal
signal.pause()Wait until a signal is received
signal.alarm(seconds)Schedule a SIGALRM after seconds

Key Takeaways

Use signal.signal() to register a handler function for a specific signal.
Signal handlers receive the signal number and current stack frame as arguments.
Signals like SIGINT allow graceful program interruption (e.g., Ctrl+C).
Avoid blocking calls inside signal handlers to prevent issues.
Signals are delivered only to the main thread and have limited support on Windows.