On this page
  1. signal
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Graceful Shutdown Handler for Services & Daemons
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

signal

Prev: shutil | Up: stdlib_module | Next: site
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — signal
Tags: #public #python3 #stdlib


Import

import signal

Overview

Installs handlers for asynchronous OS signals (SIGINT, SIGTERM, SIGHUP, SIGWINCH) so long-running CLI tools, daemons, and terminal apps can shut down gracefully or react to terminal resizes. Always keep signal handlers minimal (set a flag or threading.Event and return immediately).

Quick Start

import signal

original = signal.getsignal(signal.SIGINT)
assert original is not None

Implementation Walkthrough

1. Graceful Shutdown Handler for Services & Daemons

Catch SIGINT (Ctrl-C) and SIGTERM (container/systemd stop) to flip a stop flag and let your main loop finish cleanup cleanly:

import signal
import threading

stop_event = threading.Event()

def _handle_stop(signum: int, _frame: object) -> None:
    stop_event.set()

def install_shutdown_handlers() -> None:
    signal.signal(signal.SIGINT, _handle_stop)
    if hasattr(signal, "SIGTERM"):
        signal.signal(signal.SIGTERM, _handle_stop)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes