CLI 目录 横向对比 FCRS-1.0 标准 /llms.txt
← 返回 CLI 目录

py-spy

$ py-spy 社区开源 中风险
Ben Frederickson · 代码托管与研发协同 · MIT · macos / linux / windows

py-spy 基于 Rust 实现,无需修改代码或重启即可从外部采样正在运行的 Python 进程。Agent 可用 py-spy record --duration 10 --format speedscope -o profile.json 采集限时剖析数据,或用 py-spy dump --pid <pid> 瞬时抓取所有线程调用栈。

FCRS-1.0 综合评分
78 /100
良好 (Good)
中置信度 (源码/文档)
零摩擦安装命令
brew install py-spy
CLI vs MCP 选型建议 仅 CLI 可用

操作系统级采样剖析器,需直接读取运行中 Python 进程内存,无法由远程 MCP 替代。

Agent 友好度体检单

✓ 原生 JSON 输出
— 字段裁剪
✓ 无头非交互
— 支持 Dry-Run
— 只读模式开关
— 支持 NO_COLOR
✓ 自省/Schema 发现
— 官方 SKILL.md

当前为静态评估(本机尚未安装或尚未运行探针)。可在本地运行 npm run data:probe 并提交 data/probes/ 升级为实测证据。

FCRS-1.0 六维评分拆解

Agent 友好度 19 / 25

dump 与带时限的 record --duration 可非交互运行并输出 --format speedscope / chrometrace JSON,但 py-spy top 是阻塞式 TUI。

  • --format speedscope and --format chrometrace emit JSON files
  • py-spy top opens an interactive terminal UI
安全与权限边界 19 / 25

进程外只读内存采样不会修改目标进程状态,但按 --pid 挂载在 Linux 与 macOS 上常需要 ptrace 或 root 权限。

  • Out-of-process sampling requires CAP_SYS_PTRACE or sudo on attach
安装与运行摩擦 13 / 15

单一编译好的 Rust 二进制,可通过 brew、pip 与 cargo 在 macOS、Linux 与 Windows 安装。

  • Prebuilt wheels and Homebrew formula across all 3 OSes
能力覆盖与边际价值 12 / 15

极低开销排查线上 Python 性能瓶颈,支持 --native 采集 C 扩展栈帧及 --subprocesses。

  • Zero-instrumentation sampling with --native and --subprocesses
维护与来源背书 8 / 10

由 benfred/py-spy 维护,MIT 开源协议,在 Python 生产排障中广受认可。

  • Standard Python sampling profiler in production environments
文档与可验证性 7 / 10

README 与子命令 --help 对输出格式、参数及容器权限限制说明清晰。

  • Documented Docker SYS_PTRACE and OS caveats in README

安全边界、鉴权与放权指南

鉴权方式
无需鉴权
凭证存储位置

无需凭证;通过操作系统的 process_vm_readv / vm_read 接口只读访问目标 Python 进程内存。

潜在副作用
只读查询 本地写入
费用与配额提示

MIT 开源 Rust/Python CLI,完全免费。

可复制到 CLAUDE.md / AGENTS.md 的安全护栏
# 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 高频安全命令配方

只读查询(安全推荐)

按 PID 导出当前 Python 线程调用栈
py-spy dump --pid 12345

立即向终端打印 PID 12345 所有活动线程的调用栈,不写入文件。

受控写入与预演

录制 10 秒 Speedscope JSON 性能剖析文件
py-spy record --duration 10 --format speedscope -o profile.json -- python app.py

对 app.py 采样 10 秒,并将结构化 Speedscope JSON 剖析数据写入 profile.json。

核心优势

  • + 零代码侵入附加到运行中 Python 进程,性能开销极低。
  • + 通过 record --format 导出机器可读的 speedscope 与 chrometrace JSON 剖析文件。
  • + py-spy dump 可瞬时定位阻塞或死锁线程。

注意事项与踩坑点

  • ! py-spy top 为交互式 TUI,会阻塞 Agent 会话。
  • ! 在受限沙箱中附加已有 PID 时通常因缺少 sudo 或 SYS_PTRACE 权限而失败。

已验证兼容的 Agent 宿主

Claude Code Codex CLI Gemini CLI