Claude Code for faulthandler: Python Crash Debug Dump — Claude Skills 360 Blog
Blog / AI / Claude Code for faulthandler: Python Crash Debug Dump
AI

Claude Code for faulthandler: Python Crash Debug Dump

Published: December 18, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s faulthandler module dumps Python tracebacks on low-level faults (segfaults, etc.) and on demand — essential for debugging crashes in C extensions. import faulthandler. Enable: faulthandler.enable(file=sys.stderr, all_threads=True) — installs handlers for SIGSEGV, SIGFPE, SIGABRT, SIGBUS, SIGILL; all_threads=True includes all thread stacks. Disable: faulthandler.disable(). Check: faulthandler.is_enabled()bool. Dump now: faulthandler.dump_traceback(file=sys.stderr, all_threads=True) — prints current stacks without waiting for a crash. Timed dump: faulthandler.dump_traceback_later(timeout, repeat=False, file=sys.stderr) — fires after timeout seconds; repeat=True re-schedules on each fire (watchdog pattern). Cancel: faulthandler.cancel_dump_traceback_later(). Custom signal: faulthandler.register(signum, file=sys.stderr, all_threads=True, chain=False) — dump on any POSIX signal (e.g. SIGUSR1); chain=True also calls the previous handler. Unregister: faulthandler.unregister(signum). File arg: accepts a file object (open(...)) or a file descriptor (int). Also activatable via PYTHONFAULTHANDLER=1 env variable or python -X faulthandler. Claude Code generates crash reporters, deadlock detectors, timeout watchdogs, and production process monitors.

CLAUDE.md for faulthandler

## faulthandler Stack
- Stdlib: import faulthandler, signal, sys
- Enable: faulthandler.enable()            # call at process startup
- Dump:   faulthandler.dump_traceback()    # immediate stack dump
- Watchdog: faulthandler.dump_traceback_later(30, repeat=True)
- Signal: faulthandler.register(signal.SIGUSR1)  # dump on SIGUSR1
- Env:    PYTHONFAULTHANDLER=1   OR  python -X faulthandler
- Note:   enable() is idempotent and cheap; always enable in production

faulthandler Crash Debug Pipeline

# app/faulthandlerutil.py — enable, dump, watchdog, crash reporter, deadlock
from __future__ import annotations

import contextlib
import faulthandler
import io
import os
import signal
import sys
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic enable / status helpers
# ─────────────────────────────────────────────────────────────────────────────

def enable_faulthandler(
    file=None,
    all_threads: bool = True,
) -> None:
    """
    Enable the fault handler if not already enabled.
    Defaults to stderr with all_threads=True.

    Example:
        enable_faulthandler()
    """
    if not faulthandler.is_enabled():
        faulthandler.enable(file=file or sys.stderr, all_threads=all_threads)


def faulthandler_status() -> dict:
    """
    Return a status dict with enabled flag and registered signals.

    Example:
        print(faulthandler_status())
    """
    return {
        "enabled": faulthandler.is_enabled(),
        "platform": sys.platform,
    }


def dump_all_threads(file=None) -> None:
    """
    Immediately dump the current traceback of all threads.

    Example:
        dump_all_threads()
    """
    faulthandler.dump_traceback(
        file=file or sys.stderr,
        all_threads=True,
    )


def capture_traceback_string(all_threads: bool = True) -> str:
    """
    Capture faulthandler.dump_traceback output as a string.

    Example:
        tb_str = capture_traceback_string()
        print(tb_str[:300])
    """
    buf = io.StringIO()
    faulthandler.dump_traceback(file=buf, all_threads=all_threads)
    return buf.getvalue()


# ─────────────────────────────────────────────────────────────────────────────
# 2. File-backed crash log
# ─────────────────────────────────────────────────────────────────────────────

class CrashLog:
    """
    Route fault-handler output to a file so crash tracebacks survive process death.

    Example:
        crash_log = CrashLog("/var/log/myapp/crashes.txt")
        crash_log.enable()
        # ... run application ...
        crash_log.disable()
    """

    def __init__(self, path: "str | Path", all_threads: bool = True) -> None:
        self._path = Path(path)
        self._all_threads = all_threads
        self._file = None

    def enable(self) -> None:
        """Open log file and enable fault handler writing to it."""
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._file = self._path.open("a")
        faulthandler.enable(file=self._file, all_threads=self._all_threads)

    def disable(self) -> None:
        """Disable fault handler and close the log file."""
        faulthandler.disable()
        if self._file:
            try:
                self._file.close()
            except Exception:
                pass
            self._file = None

    def __enter__(self) -> "CrashLog":
        self.enable()
        return self

    def __exit__(self, *_: object) -> None:
        self.disable()


# ─────────────────────────────────────────────────────────────────────────────
# 3. Watchdog timer
# ─────────────────────────────────────────────────────────────────────────────

class FaultWatchdog:
    """
    Arm a repeating dump_traceback_later watchdog.
    If the process becomes unresponsive (e.g. deadlock), the watchdog
    dumps all thread stacks to the log file.

    Example:
        with FaultWatchdog(timeout=30, log_path="/tmp/watchdog.log"):
            do_long_operation()
        # watchdog disarmed automatically on exit
    """

    def __init__(
        self,
        timeout: float,
        log_path: "str | Path | None" = None,
        repeat: bool = True,
    ) -> None:
        self._timeout = timeout
        self._log_path = Path(log_path) if log_path else None
        self._repeat = repeat
        self._file = None

    def arm(self) -> None:
        """Start the watchdog timer."""
        if self._log_path:
            self._log_path.parent.mkdir(parents=True, exist_ok=True)
            self._file = self._log_path.open("a")
            f = self._file
        else:
            f = sys.stderr
        faulthandler.dump_traceback_later(
            self._timeout,
            repeat=self._repeat,
            file=f,
        )

    def disarm(self) -> None:
        """Cancel the watchdog timer."""
        faulthandler.cancel_dump_traceback_later()
        if self._file:
            try:
                self._file.close()
            except Exception:
                pass
            self._file = None

    def __enter__(self) -> "FaultWatchdog":
        self.arm()
        return self

    def __exit__(self, *_: object) -> None:
        self.disarm()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Signal-triggered traceback dump
# ─────────────────────────────────────────────────────────────────────────────

_registered_signals: list[int] = []


def register_dump_signal(
    signum: int = signal.SIGUSR1 if hasattr(signal, "SIGUSR1") else 0,
    file=None,
    all_threads: bool = True,
) -> bool:
    """
    Register a signal that triggers a traceback dump (default SIGUSR1).
    Send the signal with: kill -USR1 <pid>
    Returns True if registration succeeded.

    Example:
        register_dump_signal()
        print(f"Send SIGUSR1 to PID {os.getpid()} for a stack dump")
    """
    if signum == 0 or not hasattr(faulthandler, "register"):
        return False
    faulthandler.register(
        signum,
        file=file or sys.stderr,
        all_threads=all_threads,
        chain=False,
    )
    _registered_signals.append(signum)
    return True


def unregister_all_dump_signals() -> None:
    """Unregister all previously registered dump signals."""
    for sig in _registered_signals:
        faulthandler.unregister(sig)
    _registered_signals.clear()


# ─────────────────────────────────────────────────────────────────────────────
# 5. Deadlock detector
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class DeadlockDetector:
    """
    Run a callable in a thread with a watchdog that dumps stacks if it takes
    longer than timeout seconds, helping diagnose deadlocks.

    Example:
        def tricky():
            lock = threading.Lock()
            lock.acquire()
            lock.acquire()  # deadlock

        detector = DeadlockDetector(timeout=2.0, log_path="/tmp/deadlock.log")
        try:
            detector.run(tricky)
        except TimeoutError:
            print("deadlock detected — check /tmp/deadlock.log")
    """
    timeout:  float
    log_path: "str | Path | None" = None

    def run(self, fn, *args, **kwargs) -> object:
        """
        Run fn in the current thread with a watchdog.
        Raises TimeoutError if the watchdog fires (fn hasn't returned).
        """
        result_holder: list = []
        exc_holder: list = []
        done = threading.Event()

        def target():
            try:
                result_holder.append(fn(*args, **kwargs))
            except Exception as e:
                exc_holder.append(e)
            finally:
                done.set()

        t = threading.Thread(target=target, daemon=True)

        with FaultWatchdog(self.timeout, log_path=self.log_path, repeat=False):
            t.start()
            finished = done.wait(timeout=self.timeout + 0.5)

        if not finished:
            raise TimeoutError(
                f"Function {fn.__name__!r} did not complete within "
                f"{self.timeout}s — traceback dumped"
            )
        if exc_holder:
            raise exc_holder[0]
        return result_holder[0] if result_holder else None


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

if __name__ == "__main__":
    import tempfile

    print("=== faulthandler demo ===")

    # ── enable / status ────────────────────────────────────────────────────────
    print("\n--- status before enable ---")
    print(f"  {faulthandler_status()}")
    enable_faulthandler()
    print("\n--- status after enable ---")
    print(f"  {faulthandler_status()}")

    # ── capture traceback string ───────────────────────────────────────────────
    print("\n--- capture_traceback_string ---")
    tb = capture_traceback_string(all_threads=True)
    lines = tb.strip().splitlines()
    print(f"  captured {len(lines)} lines")
    for line in lines[:4]:
        print(f"    {line}")

    # ── CrashLog ──────────────────────────────────────────────────────────────
    print("\n--- CrashLog ---")
    with tempfile.TemporaryDirectory() as td:
        log_path = Path(td) / "crash.log"
        with CrashLog(log_path) as cl:
            # Simulate writing a manual dump
            faulthandler.dump_traceback(file=cl._file or sys.stderr)
        if log_path.exists():
            content = log_path.read_text()
            print(f"  crash.log size: {len(content)} bytes")
            print(f"  first line: {content.splitlines()[0]!r}")

    # ── FaultWatchdog ─────────────────────────────────────────────────────────
    print("\n--- FaultWatchdog (short timeout) ---")
    with tempfile.TemporaryDirectory() as td:
        wd_log = Path(td) / "watchdog.log"
        start = time.monotonic()
        with FaultWatchdog(timeout=0.3, log_path=wd_log, repeat=False):
            # Do nothing — watchdog fires after 0.3s
            time.sleep(0.5)
        elapsed = time.monotonic() - start
        print(f"  elapsed: {elapsed:.2f}s")
        if wd_log.exists():
            print(f"  watchdog log size: {wd_log.stat().st_size} bytes")

    # ── register_dump_signal ──────────────────────────────────────────────────
    print("\n--- register_dump_signal ---")
    if hasattr(signal, "SIGUSR1"):
        ok = register_dump_signal(signal.SIGUSR1)
        print(f"  SIGUSR1 registered: {ok}")
        print(f"  send 'kill -USR1 {os.getpid()}' to dump stacks")
        unregister_all_dump_signals()
        print(f"  unregistered all dump signals")
    else:
        print("  SIGUSR1 not available on this platform")

    # ── DeadlockDetector ──────────────────────────────────────────────────────
    print("\n--- DeadlockDetector ---")
    with tempfile.TemporaryDirectory() as td:
        dd = DeadlockDetector(timeout=0.2, log_path=Path(td) / "dd.log")
        # Fast function — should succeed
        result = dd.run(lambda: 42)
        print(f"  fast function result: {result}")

        # Slow function — should time out
        try:
            dd.run(lambda: time.sleep(5))
        except TimeoutError as e:
            print(f"  slow function: TimeoutError raised (expected)")

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

For the signal module alternative — signal.signal(signal.SIGUSR1, handler) lets you register a Python-level callback on POSIX signals — use signal when you need a full Python callback that accesses application state on the signal; use faulthandler.register(signum) when you only need a stack dump (it fires at C level even if the GIL is held, making it safe for diagnosing deadlocks where Python-level signal handlers would never run). For the traceback.print_stack / threading.enumerate alternative — walking threading.enumerate() and calling traceback.extract_stack(sys._current_frames()[t.ident]) produces thread stacks from Python — use this approach when you want to process stack frames programmatically (filter, format, log to JSON); use faulthandler.dump_traceback() when you need a low-level signal-safe dump that bypasses the GIL and works even during interpreter-level crashes. The Claude Skills 360 bundle includes faulthandler skill sets covering enable_faulthandler()/faulthandler_status()/dump_all_threads()/capture_traceback_string() core helpers, CrashLog file-backed crash log context manager, FaultWatchdog repeating dump_traceback_later context manager, register_dump_signal()/unregister_all_dump_signals() SIGUSR1 helpers, and DeadlockDetector.run() with timeout and watchdog integration. Start with the free tier to try crash debug patterns and faulthandler 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