py-spy attaches to a running CPython process or launches one, sampling stacks without code changes and reporting via top, dump, or recorded flame graphs.
Overview
py-spy is a sampling profiler for CPython programs. It inspects a live interpreter from outside the target process, which keeps overhead low enough for many production workloads and avoids injecting profiling hooks into application code.
The record subcommand writes interactive flame graphs, speedscope files, or raw samples. top shows a live ranking of hot functions similar to Unix top. dump prints current per-thread Python stack traces, with optional local variable details when requested.
Stack reconstruction reads process memory via OS-specific APIs, walking interpreter structures across supported CPython versions on Linux, macOS, Windows, and FreeBSD. Optional modes profile native extensions, follow child processes, filter to GIL-holding threads, or reduce pause time at the cost of occasional incomplete stacks.
Distribution includes PyPI wheels, GitHub release binaries, Homebrew on macOS, and distro packages. Container and Kubernetes notes describe elevated ptrace capabilities needed to read memory from other containers.
Key features
- Attach-by-PID or launch-and-profile
- Flame graph and speedscope export
- Live top-style dashboard
- Instant stack dump command
- Native extension stack samples
- Subprocess and multiprocessing follow
- GIL-aware thread filtering
- Non-pausing sampling option
Use cases
- Production latency investigations
- Hung Python process diagnosis
- Flame graph performance tuning
- Profiling without redeploying code
- Containerized service stack traces