py-spy
$ py-spy 社区开源 中风险py-spy 基于 Rust 实现,无需修改代码或重启即可从外部采样正在运行的 Python 进程。Agent 可用 py-spy record --duration 10 --format speedscope -o profile.json 采集限时剖析数据,或用 py-spy dump --pid <pid> 瞬时抓取所有线程调用栈。
brew install py-spy 操作系统级采样剖析器,需直接读取运行中 Python 进程内存,无法由远程 MCP 替代。
Agent 友好度体检单
当前为静态评估(本机尚未安装或尚未运行探针)。可在本地运行 npm run data:probe 并提交 data/probes/ 升级为实测证据。
FCRS-1.0 六维评分拆解
dump 与带时限的 record --duration 可非交互运行并输出 --format speedscope / chrometrace JSON,但 py-spy top 是阻塞式 TUI。
--format speedscopeand--format chrometraceemit JSON filespy-spy topopens an interactive terminal UI
进程外只读内存采样不会修改目标进程状态,但按 --pid 挂载在 Linux 与 macOS 上常需要 ptrace 或 root 权限。
- Out-of-process sampling requires
CAP_SYS_PTRACEorsudoon attach
单一编译好的 Rust 二进制,可通过 brew、pip 与 cargo 在 macOS、Linux 与 Windows 安装。
- Prebuilt wheels and Homebrew formula across all 3 OSes
极低开销排查线上 Python 性能瓶颈,支持 --native 采集 C 扩展栈帧及 --subprocesses。
- Zero-instrumentation sampling with
--nativeand--subprocesses
由 benfred/py-spy 维护,MIT 开源协议,在 Python 生产排障中广受认可。
- Standard Python sampling profiler in production environments
README 与子命令 --help 对输出格式、参数及容器权限限制说明清晰。
- Documented Docker
SYS_PTRACEand OS caveats in README
安全边界、鉴权与放权指南
无需凭证;通过操作系统的 process_vm_readv / vm_read 接口只读访问目标 Python 进程内存。
MIT 开源 Rust/Python CLI,完全免费。
# py-spy Agent Rules - Always pass `--duration <seconds>` on `py-spy record` and avoid `py-spy top` (which runs an interactive TUI). - Use `--format speedscope` or `--format chrometrace` when machine-parseable JSON output is needed. - Note that attaching to an existing `--pid` often requires `sudo` or `CAP_SYS_PTRACE`.
Agent 高频安全命令配方
只读查询(安全推荐)
py-spy dump --pid 12345
立即向终端打印 PID 12345 所有活动线程的调用栈,不写入文件。
受控写入与预演
py-spy record --duration 10 --format speedscope -o profile.json -- python app.py
对 app.py 采样 10 秒,并将结构化 Speedscope JSON 剖析数据写入 profile.json。
核心优势
- + 零代码侵入附加到运行中 Python 进程,性能开销极低。
- + 通过
record --format导出机器可读的speedscope与chrometraceJSON 剖析文件。 - +
py-spy dump可瞬时定位阻塞或死锁线程。
注意事项与踩坑点
- !
py-spy top为交互式 TUI,会阻塞 Agent 会话。 - ! 在受限沙箱中附加已有 PID 时通常因缺少
sudo或SYS_PTRACE权限而失败。