Claude Code for signal: Python Unix Signal Handling — Claude Skills 360 Blog
Blog / AI / Claude Code for signal: Python Unix Signal Handling
AI

Claude Code for signal: Python Unix Signal Handling

Published: September 14, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s signal module intercepts Unix signals for graceful shutdown, timeouts, and daemon lifecycle management. import signal. signal.signal: signal.signal(signal.SIGTERM, handler) — register handler(signum, frame) for a signal; only the main thread can register handlers. SIG_DFL / SIG_IGN: signal.signal(signal.SIGHUP, signal.SIG_IGN) — ignore; signal.SIG_DFL restores OS default. getsignal: signal.getsignal(signal.SIGINT) → current handler. raise_signal: signal.raise_signal(signal.SIGUSR1) — send to self (Python 3.8+). alarm: signal.alarm(5) — schedules SIGALRM in 5 seconds (Unix only); signal.alarm(0) cancels. setitimer: signal.setitimer(signal.ITIMER_REAL, 1.5) — floating-point alarm; fires SIGALRM at interval. Signals: signal.Signals.SIGTERM (15), signal.SIGINT (2), signal.SIGHUP (1), signal.SIGCHLD (17), signal.SIGUSR1 (10), signal.SIGUSR2 (12). strsignal: signal.strsignal(signal.SIGTERM) → “Terminated”. sigwait: sig = signal.sigwait({signal.SIGUSR1, signal.SIGTERM}) — block until one arrives (use in threads). pthread_kill: signal.pthread_kill(tid, signal.SIGUSR1) — send to a specific thread. signal.valid_signals() → set of all valid signal numbers. Limitations: handlers run in the main thread only; use threading.Event or queues to relay signals to worker threads. Claude Code generates graceful shutdown managers, timeout decorators, daemon reload handlers, and child-process reaping utilities.

CLAUDE.md for signal

## signal Stack
- Stdlib: import signal, os, threading
- Handle: signal.signal(signal.SIGTERM, lambda s, f: shutdown_event.set())
- Ignore: signal.signal(signal.SIGHUP, signal.SIG_IGN)
- Alarm:  signal.alarm(10)  # SIGALRM in 10s (Unix only)
- Names:  signal.strsignal(signum)
- Thread: use threading.Event / queue.Queue to relay signal to worker threads

signal Signal Handling Pipeline

# app/signalutil.py — shutdown, timeout, reload, child reap, signal relay
from __future__ import annotations

import os
import queue
import signal
import sys
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Generator, TypeVar

T = TypeVar("T")

_IS_UNIX = sys.platform != "win32"


# ─────────────────────────────────────────────────────────────────────────────
# 1. Graceful shutdown manager
# ─────────────────────────────────────────────────────────────────────────────

class ShutdownManager:
    """
    Registers SIGTERM and SIGINT handlers and provides a threading.Event
    that is set when a termination signal arrives.
    Optionally calls a cleanup callback.

    Example:
        sm = ShutdownManager()
        sm.install()
        while not sm.should_exit:
            do_work()
        sm.wait()
    """

    def __init__(self, signals: list[int] | None = None) -> None:
        self._sigs = signals or [signal.SIGTERM, signal.SIGINT]
        self._event = threading.Event()
        self._callbacks: list[Callable[[], None]] = []
        self._signum: int | None = None

    def on_shutdown(self, fn: Callable[[], None]) -> None:
        """Register a cleanup callback invoked when a shutdown signal arrives."""
        self._callbacks.append(fn)

    def install(self) -> "ShutdownManager":
        """Install signal handlers. Must be called from the main thread."""
        for sig in self._sigs:
            signal.signal(sig, self._handler)
        return self

    def uninstall(self) -> None:
        """Restore SIG_DFL for all managed signals."""
        for sig in self._sigs:
            signal.signal(sig, signal.SIG_DFL)

    def _handler(self, signum: int, frame: Any) -> None:
        self._signum = signum
        for cb in self._callbacks:
            try:
                cb()
            except Exception:
                pass
        self._event.set()

    @property
    def should_exit(self) -> bool:
        return self._event.is_set()

    def wait(self, timeout: float | None = None) -> bool:
        """Block until a shutdown signal is received or timeout expires."""
        return self._event.wait(timeout=timeout)

    @property
    def signal_name(self) -> str:
        if self._signum is None:
            return "none"
        return signal.strsignal(self._signum) or str(self._signum)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Signal-based timeout (Unix only — uses SIGALRM)
# ─────────────────────────────────────────────────────────────────────────────

class SignalTimeout(Exception):
    """Raised when a signal-based timeout expires."""


@contextmanager
def alarm_timeout(seconds: float) -> Generator[None, None, None]:
    """
    Context manager that raises SignalTimeout after `seconds`.
    Unix-only (uses SIGALRM). Must run in the main thread.

    Example:
        try:
            with alarm_timeout(5.0):
                slow_operation()
        except SignalTimeout:
            print("operation timed out")
    """
    if not _IS_UNIX:
        yield
        return

    def _handler(signum: int, frame: Any) -> None:
        raise SignalTimeout(f"operation timed out after {seconds}s")

    old_handler = signal.signal(signal.SIGALRM, _handler)
    signal.setitimer(signal.ITIMER_REAL, seconds)
    try:
        yield
    finally:
        signal.setitimer(signal.ITIMER_REAL, 0)
        signal.signal(signal.SIGALRM, old_handler)


def run_with_alarm_timeout(fn: Callable[[], T], seconds: float, default: T | None = None) -> T | None:
    """
    Run fn(); return result or default if SIGALRM fires first.
    Unix-only.

    Example:
        result = run_with_alarm_timeout(slow_fn, 3.0, default=None)
    """
    try:
        with alarm_timeout(seconds):
            return fn()
    except SignalTimeout:
        return default


# ─────────────────────────────────────────────────────────────────────────────
# 3. Signal relay to worker threads
# ─────────────────────────────────────────────────────────────────────────────

class SignalRelay:
    """
    Bridges signal handlers (main-thread-only) to worker threads via a queue.
    Workers can consume SignalEvents from the relay's queue.

    Example:
        relay = SignalRelay([signal.SIGUSR1, signal.SIGHUP])
        relay.install()

        def worker():
            while True:
                event = relay.get(timeout=1.0)
                if event:
                    print(f"received {event.name}")

        thread = threading.Thread(target=worker, daemon=True)
        thread.start()
    """

    @dataclass
    class SignalEvent:
        signum: int

        @property
        def name(self) -> str:
            return signal.strsignal(self.signum) or str(self.signum)

    def __init__(self, signals: list[int]) -> None:
        self._sigs = signals
        self._queue: queue.Queue["SignalRelay.SignalEvent"] = queue.Queue()

    def install(self) -> "SignalRelay":
        for sig in self._sigs:
            signal.signal(sig, self._handler)
        return self

    def _handler(self, signum: int, frame: Any) -> None:
        self._queue.put_nowait(SignalRelay.SignalEvent(signum=signum))

    def get(self, timeout: float | None = None) -> "SignalRelay.SignalEvent | None":
        try:
            return self._queue.get(timeout=timeout)
        except queue.Empty:
            return None


# ─────────────────────────────────────────────────────────────────────────────
# 4. SIGHUP reload pattern
# ─────────────────────────────────────────────────────────────────────────────

class ReloadManager:
    """
    Listens for SIGHUP and invokes a reload callback.
    Typical use: reload configuration without restarting the process.

    Example:
        def reload_config():
            global CONFIG
            CONFIG = load_config("app.toml")
            print("Config reloaded")

        rlm = ReloadManager(reload_config)
        rlm.install()
    """

    def __init__(self, callback: Callable[[], None]) -> None:
        self._callback = callback
        self._reload_count = 0

    def install(self) -> "ReloadManager":
        if _IS_UNIX:
            signal.signal(signal.SIGHUP, self._handler)
        return self

    def _handler(self, signum: int, frame: Any) -> None:
        self._reload_count += 1
        self._callback()

    @property
    def reload_count(self) -> int:
        return self._reload_count


# ─────────────────────────────────────────────────────────────────────────────
# 5. Child process reaping (SIGCHLD)
# ─────────────────────────────────────────────────────────────────────────────

class ChildReaper:
    """
    Installs a SIGCHLD handler that reaps zombie children automatically.
    Records (pid, exit_status) for each reaped child.

    Example:
        reaper = ChildReaper()
        reaper.install()
        pid = os.fork()
        if pid == 0:
            sys.exit(0)   # child exits
        time.sleep(0.1)
        print(reaper.reaped)
    """

    def __init__(self) -> None:
        self.reaped: list[tuple[int, int]] = []
        self._lock = threading.Lock()

    def install(self) -> "ChildReaper":
        if _IS_UNIX:
            signal.signal(signal.SIGCHLD, self._handler)
        return self

    def _handler(self, signum: int, frame: Any) -> None:
        while True:
            try:
                pid, status = os.waitpid(-1, os.WNOHANG)
                if pid == 0:
                    break
                with self._lock:
                    self.reaped.append((pid, status))
            except ChildProcessError:
                break


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== signal demo ===")

    # ── ShutdownManager (send SIGUSR1 to self to simulate) ────────────────────
    print("\n--- ShutdownManager ---")
    sm = ShutdownManager(signals=[signal.SIGUSR1])
    cleanup_called = []
    sm.on_shutdown(lambda: cleanup_called.append(True))
    sm.install()

    # Simulate signal from a background thread
    def _send_sig():
        time.sleep(0.05)
        signal.raise_signal(signal.SIGUSR1)

    threading.Thread(target=_send_sig, daemon=True).start()
    exited = sm.wait(timeout=2.0)
    sm.uninstall()
    print(f"  should_exit={sm.should_exit}  signal={sm.signal_name}  cleanup_called={cleanup_called}")

    # ── alarm_timeout ─────────────────────────────────────────────────────────
    if _IS_UNIX:
        print("\n--- alarm_timeout (success) ---")
        try:
            with alarm_timeout(2.0):
                time.sleep(0.01)
            print("  completed before timeout")
        except SignalTimeout:
            print("  timed out (unexpected)")

        print("\n--- alarm_timeout (timeout fires) ---")
        try:
            with alarm_timeout(0.05):
                time.sleep(5.0)  # will be interrupted
        except SignalTimeout:
            print("  SignalTimeout raised as expected")
    else:
        print("\n--- alarm_timeout skipped (Windows) ---")

    # ── SignalRelay ────────────────────────────────────────────────────────────
    if _IS_UNIX:
        print("\n--- SignalRelay ---")
        relay = SignalRelay([signal.SIGUSR2])
        relay.install()

        received = []
        def _worker():
            event = relay.get(timeout=1.0)
            if event:
                received.append(event.name)

        t = threading.Thread(target=_worker, daemon=True)
        t.start()
        time.sleep(0.01)
        signal.raise_signal(signal.SIGUSR2)
        t.join(timeout=1.5)
        print(f"  relay received: {received}")

    # ── strsignal / Signals enum ──────────────────────────────────────────────
    print("\n--- signal names ---")
    for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGUSR1]:
        print(f"  {sig}: {signal.strsignal(sig)}")

    print("\n=== done ===")

For the atexit alternative — atexit.register(fn) adds a callback executed when the Python interpreter exits normally (after sys.exit() or when the main module finishes) but NOT on SIGKILL, SIGTERM, or unhandled SIGINT unless caught first — use atexit for cleanup that should run on normal program exit (flushing logs, closing files); combine both: install a signal.signal(SIGTERM, ...) handler that calls sys.exit() so atexit handlers also fire on SIGTERM. For the threading.Event alternative — threading.Event used alongside signal handlers provides a safer inter-thread communication pattern than setting global flags in signal handlers; signal handlers in Python are restricted to the main thread and can only atomically update simple data types (integers, threading.Event.set()) — use threading.Event or queue.Queue (as shown in SignalRelay above) to communicate signal arrivals to worker threads; never call complex functions or I/O directly inside a signal handler. The Claude Skills 360 bundle includes signal skill sets covering ShutdownManager with install()/uninstall()/wait()/signal_name, SignalTimeout exception with alarm_timeout() context manager and run_with_alarm_timeout(), SignalRelay queue-bridged multi-thread signal delivery, ReloadManager SIGHUP config-reload pattern, and ChildReaper SIGCHLD zombie reaper. Start with the free tier to try Unix signal patterns and signal pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free