Claude Code for py-spy: Sampling Profiler for Running Python Processes — Claude Skills 360 Blog
Blog / AI / Claude Code for py-spy: Sampling Profiler for Running Python Processes
AI

Claude Code for py-spy: Sampling Profiler for Running Python Processes

Published: May 3, 2028
Read time: 5 min read
By: Claude Skills 360

py-spy profiles Python processes without modifying or restarting them. pip install py-spy. Top (live): py-spy top --pid <PID>. Record flamegraph: py-spy record -o profile.svg --pid <PID>. Duration: py-spy record -o p.svg --pid <PID> --duration 30. New process: py-spy record -o p.svg -- python script.py. Speedscope: py-spy record -o p.json --format speedscope --pid <PID>. Dump: py-spy dump --pid <PID> — one-shot stack snapshot to stdout. Native: py-spy record --native --pid <PID> — include C extension frames. Subprocesses: py-spy record --subprocesses --pid <PID>. Rate: py-spy record --rate 100 --pid <PID> — 100 samples/sec (default 100). Idle: py-spy record --idle --pid <PID> — include threads waiting on I/O. GIL: py-spy top --gil --pid <PID> — show GIL contention. Threads: py-spy dump --pid <PID> --full — all threads and their current frame. Docker: docker exec <ctr> py-spy top --pid 1. py-spy record --pid $(pgrep -f myapp.py) -o /tmp/profile.svg. Output SVG: default. HTML: --format html. Programmatic: import py_spy; stacks = py_spy.get_stacks(pid=<PID>). Claude Code generates py-spy profiling scripts, process monitoring automation, and production flamegraph capture tools.

CLAUDE.md for py-spy

## py-spy Stack
- Version: py-spy >= 0.3 | pip install py-spy
- Record: py-spy record -o profile.svg --pid <PID> [--duration 30]
- New process: py-spy record -o profile.svg -- python script.py
- Top: py-spy top --pid <PID>  — htop-style live view
- Dump: py-spy dump --pid <PID>  — instant stack snapshot
- Native: --native  | Subprocesses: --subprocesses  | Idle: --idle

py-spy Profiling Pipeline

# app/pyspy_utils.py — py-spy record, dump, top, and automation helpers
from __future__ import annotations

import os
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path
from typing import Any


# ─────────────────────────────────────────────────────────────────────────────
# 1. Check py-spy availability
# ─────────────────────────────────────────────────────────────────────────────

def _pyspy() -> str:
    """Return the py-spy executable path, raising if not found."""
    exe = shutil.which("py-spy")
    if exe:
        return exe
    # Try module invocation
    result = subprocess.run(
        [sys.executable, "-m", "py_spy", "--version"],
        capture_output=True,
    )
    if result.returncode == 0:
        return f"{sys.executable} -m py_spy"
    raise RuntimeError(
        "py-spy not found. Install with: pip install py-spy\n"
        "Note: recording may require sudo on Linux."
    )


def pyspy_available() -> bool:
    """Return True if py-spy is installed and accessible."""
    try:
        _pyspy()
        return True
    except RuntimeError:
        return False


# ─────────────────────────────────────────────────────────────────────────────
# 2. Record — attach to running process
# ─────────────────────────────────────────────────────────────────────────────

def record_pid(
    pid: int,
    output: str | Path = "/tmp/profile.svg",
    duration: int | None = 30,
    rate: int = 100,
    native: bool = False,
    subprocesses: bool = False,
    idle: bool = False,
    fmt: str = "svg",
) -> Path:
    """
    Record a flamegraph for an already-running Python process.
    Attaches non-intrusively via ptrace (Linux) / task_info (macOS).

    pid:          PID of the Python process to profile.
    output:       output file path (extension ignored; use fmt).
    duration:     seconds to record (None = record until Ctrl+C).
    rate:         samples per second (default 100).
    native:       include C extension frames.
    subprocesses: also profile child processes.
    idle:         include threads blocked on I/O or sleep.
    fmt:          "svg", "html", "speedscope", "raw".

    Note: may require `sudo` on Linux unless kernel.perf_event_paranoid ≤ 1.

    Returns path to the generated file.
    """
    out   = Path(output).with_suffix(f".{fmt}")
    cmd   = ["py-spy", "record", "-o", str(out), "--format", fmt,
             "--rate", str(rate), "--pid", str(pid)]
    if duration is not None:
        cmd += ["--duration", str(duration)]
    if native:
        cmd.append("--native")
    if subprocesses:
        cmd.append("--subprocesses")
    if idle:
        cmd.append("--idle")

    subprocess.run(cmd, check=True)
    return out


def record_script(
    script: str | list[str],
    output: str | Path = "/tmp/profile.svg",
    rate: int = 100,
    native: bool = False,
    fmt: str = "svg",
) -> Path:
    """
    Launch a Python script under py-spy and record until it exits.
    script: single python file path, or list of args like ["python", "app.py", "--arg"].

    Example:
        path = record_script("benchmarks/sort_bench.py", output="/tmp/sort.svg")
    """
    out  = Path(output).with_suffix(f".{fmt}")
    cmd  = ["py-spy", "record", "-o", str(out), "--format", fmt, "--rate", str(rate)]
    if native:
        cmd.append("--native")
    if isinstance(script, str):
        cmd += ["--", sys.executable, script]
    else:
        cmd += ["--"] + list(script)

    subprocess.run(cmd, check=True)
    return out


# ─────────────────────────────────────────────────────────────────────────────
# 3. Dump — instant stack snapshot
# ─────────────────────────────────────────────────────────────────────────────

def dump_stacks(
    pid: int,
    all_threads: bool = True,
    locals_: bool = False,
) -> str:
    """
    Dump the current call stacks of a running Python process.
    Returns the text output as a string.

    Useful for: instant diagnosis of a stuck/hanged process.

    Example:
        stacks = dump_stacks(os.getpid())
        print(stacks[:2000])
    """
    cmd = ["py-spy", "dump", "--pid", str(pid)]
    if all_threads:
        cmd.append("--full")
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout + result.stderr


def dump_own_stacks() -> str:
    """Dump stacks of the current Python process (self-profiling)."""
    return dump_stacks(os.getpid())


# ─────────────────────────────────────────────────────────────────────────────
# 4. Timed profiling — record for N seconds then return path
# ─────────────────────────────────────────────────────────────────────────────

class TimedRecorder:
    """
    Attach py-spy to the current process for a fixed duration in a thread.
    Note: self-profiling on Linux requires SYS_PTRACE capability or sudo.

    Usage:
        recorder = TimedRecorder(duration=10, output="/tmp/api_50s.svg")
        recorder.start()
        # ... do work ...
        recorder.wait()
        print(f"Flamegraph: {recorder.output_path}")
    """

    def __init__(
        self,
        duration: int = 30,
        output: str | Path = "/tmp/timed_profile.svg",
        rate: int = 100,
        native: bool = False,
        fmt: str = "svg",
    ) -> None:
        self.duration    = duration
        self.output_path = Path(output).with_suffix(f".{fmt}")
        self.rate        = rate
        self.native      = native
        self.fmt         = fmt
        self._proc: subprocess.Popen | None = None

    def start(self) -> None:
        """Start recording asynchronously."""
        cmd = [
            "py-spy", "record",
            "-o", str(self.output_path),
            "--format", self.fmt,
            "--rate", str(self.rate),
            "--duration", str(self.duration),
            "--pid", str(os.getpid()),
        ]
        if self.native:
            cmd.append("--native")
        self._proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL,
                                      stderr=subprocess.DEVNULL)

    def stop(self) -> None:
        """Interrupt recording early."""
        if self._proc and self._proc.poll() is None:
            self._proc.send_signal(signal.SIGINT)

    def wait(self, timeout: float | None = None) -> None:
        """Wait for recording to complete."""
        if self._proc:
            self._proc.wait(timeout=timeout)


# ─────────────────────────────────────────────────────────────────────────────
# 5. Docker / Kubernetes helper snippets
# ─────────────────────────────────────────────────────────────────────────────

DOCKER_EXAMPLES = """
# Profile PID 1 inside a running container for 30 seconds:
docker exec -it <container_id> py-spy record -o /tmp/profile.svg --pid 1 --duration 30

# Copy the flamegraph out:
docker cp <container_id>:/tmp/profile.svg ./profile.svg

# One-shot stack dump (no file):
docker exec <container_id> py-spy dump --pid 1

# Kubernetes pod:
kubectl exec <pod> -- py-spy record -o /tmp/profile.svg --pid 1 --duration 30
kubectl cp <pod>:/tmp/profile.svg ./profile.svg
"""

GITHUB_ACTIONS_EXAMPLE = """
# In CI: profile a benchmark script and upload the flamegraph as an artifact
- name: Run profiled benchmark
  run: |
    pip install py-spy
    py-spy record -o profile.svg -- python benchmarks/bench_main.py
- uses: actions/upload-artifact@v4
  with:
    name: flamegraph
    path: profile.svg
"""


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

if __name__ == "__main__":
    if not pyspy_available():
        print("py-spy not installed. Run: pip install py-spy")
        sys.exit(1)

    print("=== Profile current script ===")
    out = record_script(
        [sys.executable, "-c",
         "import time; [sum(range(100_000)) for _ in range(50)]; time.sleep(0.1)"],
        output="/tmp/demo_profile.svg",
        rate=200,
    )
    print(f"  Flamegraph: {out}  ({out.stat().st_size:,} bytes)")

    print("\n=== Stack dump (current process) ===")
    stacks = dump_own_stacks()
    lines = stacks.strip().splitlines()
    print(f"  {len(lines)} lines of stack info")
    for line in lines[:8]:
        print(f"  {line}")

    print("\nDone. Open the SVG in a browser to explore the flamegraph.")

For the cProfile / pyinstrument alternative — cProfile and pyinstrument both require you to restart the process wrapped in their instrumentation; py-spy attaches to any running PID at any time with zero code changes, making it the only option for profiling production processes, stuck workers, or third-party code that you cannot modify. For the gdb / strace alternative — gdb and strace can dump C-level stacks but cannot map them to Python frames; py-spy understands CPython internals and translates memory addresses to Python function names, file paths, and line numbers — giving you actionable Python-level information from a binary inspection. The Claude Skills 360 bundle includes py-spy skill sets covering record_pid() with duration/rate/native/subprocesses/idle, record_script() for profiling a new process, dump_stacks()/dump_own_stacks() instant snapshot, TimedRecorder async recorder class, Docker/Kubernetes exec snippets, GitHub Actions CI profiling pattern, speedscope JSON output format, and GIL contention monitoring with —gil flag. Start with the free tier to try production process profiling 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