1 min read

Python Signal Module

The signal module provides mechanisms to use signal handlers in Python. Signals are software interrupts delivered to a process by the operating system.

Importing the Module

import signal
import sys
import time

Handling Signals

To handle a signal, you define a handler function. This function takes two arguments: the signal number and the current stack frame.

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

Registering a Handler

Use signal.signal() to register a handler for a specific signal.

# Register the handler for SIGINT (Ctrl+C)
signal.signal(signal.SIGINT, signal_handler)

print('Press Ctrl+C')
while True:
    time.sleep(1)

Common Signals

  • signal.SIGINT: Interrupt from keyboard (Ctrl+C).
  • signal.SIGTERM: Termination signal.
  • signal.SIGKILL: Kill signal (cannot be caught or ignored).
  • signal.SIGALRM: Timer signal (Unix only).

Alarms (Unix Only)

On Unix-based systems, you can use signal.alarm() to schedule a SIGALRM signal.

def handler(signum, frame):
    raise Exception("Timeout")

# Register the signal function handler
signal.signal(signal.SIGALRM, handler)

# Define a 2-second alarm
signal.alarm(2)

try:
    time.sleep(10)
except Exception as exc: 
    print(exc)

Ignoring Signals

You can ignore a signal by setting the handler to signal.SIG_IGN.

signal.signal(signal.SIGINT, signal.SIG_IGN)

programming/python/python