跳到主要内容

Python Debugpy

调试 Python:pdb REPL + debugpy 远程 (DAP)。

技能元数据

来源捆绑(默认安装)
路径skills/software-development/python-debugpy
版本1.0.0
作者Hermes Agent
许可证MIT
平台linux, macos
标签debugging, python, pdb, debugpy, breakpoints, dap, post-mortem
相关技能systematic-debugging, node-inspect-debugger

参考:完整 SKILL.md

信息

以下是 Hermes 在触发此技能时加载的完整技能定义。这是技能激活时代理所看到的指令。

Python 调试器 (pdb + debugpy)

概述

三种工具,根据情况选择:

工具适用场景
breakpoint() + pdb本地、交互式、最简单。在源代码中添加 breakpoint(),正常运行,在该行获得 REPL。
python -m pdb在无需编辑源代码的情况下,通过 pdb 启动现有脚本。适用于快速探查。
debugpy远程 / 无头模式 / “附加到已运行的进程”。使用 DAP 通信,可从终端进行脚本化控制,适用于长期运行的进程(网关、守护进程、PTY 子进程)。

breakpoint() 开始。 这是成本最低且有效的方案。

何时使用

  • 测试失败,且回溯信息未揭示值错误的原因
  • 需要单步执行函数并观察集合的变化
  • 长期运行的进程(hermes gateway, tui_gateway)行为异常且无法重启
  • 事后分析(Post-mortem):生产类代码中抛出异常,希望检查崩溃点的局部变量
  • 子进程 / 子项(Python _SlashWorker, PTY bridge worker)是实际的 bug 所在

不适用于: print() / logging.debug 能在一分钟内解决的问题,或 pytest -vv --tb=long --showlocals 已经揭示的问题。

pdb 快速参考

在任何 pdb 提示符 ((Pdb)) 中:

命令操作
h / h cmd帮助
n下一行(单步跳过)
s单步进入
r从当前函数返回
c继续
unt N继续直到第 N 行
j N跳转到第 N 行(仅限同一函数内)
l / ll列出当前行附近的源代码 / 整个函数
wwhere(堆栈跟踪)
u / d在堆栈中向上 / 向下移动
a打印当前函数的参数
p expr / pp expr打印 / 美化打印表达式
display expr每次停止时自动打印表达式
b file:line设置断点
b func在函数入口处断点
b file:line, cond条件断点
cl N清除断点 N
tbreak file:line一次性断点
!stmt执行任意 Python 语句(包括赋值)
interact在当前作用域中进入完整的 Python REPL(按 Ctrl+D 退出)
q退出

interact 命令功能最强大——你可以导入任何模块、检查复杂对象,甚至调用改变状态的方法。默认情况下局部变量是只读的;在 (Pdb) 提示符下使用 !x = 42 来进行修改。

方案 1:本地断点

最简单。编辑文件:

def compute(x, y):
result = some_helper(x)
breakpoint() # <-- drops into pdb here
return result + y

正常运行代码。你将停留在 breakpoint() 行,并完全访问局部变量。

提交前别忘了移除 breakpoint() 使用 git diff 或预提交 grep:

rg -n 'breakpoint\(\)' --type py

方案 2:在 pdb 下启动脚本(无需编辑源代码)

python -m pdb path/to/script.py arg1 arg2
# Lands at first line of script
(Pdb) b path/to/script.py:42
(Pdb) c

方案 3:调试 pytest 测试

hermes 测试运行器和 pytest 都支持此功能:

# Drop to pdb on failure (or on any raised exception):
scripts/run_tests.sh tests/path/to/test_file.py::test_name --pdb

# Drop to pdb at the START of the test:
scripts/run_tests.sh tests/path/to/test_file.py::test_name --trace

# Show locals in tracebacks without pdb:
scripts/run_tests.sh tests/path/to/test_file.py --showlocals --tb=long

注意:scripts/run_tests.sh 默认使用 xdist (-n 4),而 pdb 在 xdist 下工作。添加 -p no:xdist 或使用 -n 0 运行单个测试:

scripts/run_tests.sh tests/foo_test.py::test_bar --pdb -p no:xdist
# or
source .venv/bin/activate
python -m pytest tests/foo_test.py::test_bar --pdb

这会绕过 hermetic-env 保证——对于调试来说没问题,但在推送之前请在包装器下重新运行以确认。

方案 4:对任何异常进行事后分析

import pdb, sys
try:
run_the_thing()
except Exception:
pdb.post_mortem(sys.exc_info()[2])

或者包裹整个脚本:

python -m pdb -c continue script.py
# When it crashes, pdb catches it and you're in the frame of the exception

或者在 repl/jupyter 中设置全局钩子:

import sys
def excepthook(etype, value, tb):
import pdb; pdb.post_mortem(tb)
sys.excepthook = excepthook

方案 5:使用 debugpy 进行远程调试(附加到运行中的进程)

适用于长期运行的进程:Hermes gateway, tui_gateway, 守护进程,或者已经行为异常且无法干净重启的进程。

设置

source /home/bb/hermes-agent/.venv/bin/activate
pip install debugpy

模式 A:编辑源代码——进程在启动时等待调试器

在入口点顶部(或在你想要调试的函数内部)添加:

import debugpy
debugpy.listen(("127.0.0.1", 5678))
print("debugpy listening on 5678, waiting for client...", flush=True)
debugpy.wait_for_client()
debugpy.breakpoint() # optional: pause immediately once attached

启动进程;它将在 wait_for_client() 处阻塞。

模式 B:无需编辑源代码——使用 -m debugpy 启动

python -m debugpy --listen 127.0.0.1:5678 --wait-for-client your_script.py arg1

模块入口的等效命令:

python -m debugpy --listen 127.0.0.1:5678 --wait-for-client -m your.module

模式 C:附加到已运行的进程

需要在目标环境中预安装 PID 和 debugpy:

python -m debugpy --listen 127.0.0.1:5678 --pid <pid>
# debugpy injects itself into the process. Then attach a client as below.

某些内核/安全配置会阻止基于 ptrace 的注入(/proc/sys/kernel/yama/ptrace_scope)。修复方法:

echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

从终端连接客户端

最简单的终端侧 DAP 客户端是 VS Code CLI 或一个小脚本。在 Hermes 内部,你有两个实际可行的选项:

选项 1:debugpy 自带的 CLI REPL — 并非官方功能,而是一个微型 DAP 客户端脚本:

# /tmp/dap_client.py
import socket, json, itertools, time, sys

HOST, PORT = "127.0.0.1", 5678
s = socket.create_connection((HOST, PORT))
seq = itertools.count(1)

def send(msg):
msg["seq"] = next(seq)
body = json.dumps(msg).encode()
s.sendall(f"Content-Length: {len(body)}\r\n\r\n".encode() + body)

def recv():
header = b""
while b"\r\n\r\n" not in header:
header += s.recv(1)
length = int(header.decode().split("Content-Length:")[1].split("\r\n")[0].strip())
body = b""
while len(body) < length:
body += s.recv(length - len(body))
return json.loads(body)

send({"type": "request", "command": "initialize", "arguments": {"adapterID": "python"}})
print(recv())
send({"type": "request", "command": "attach", "arguments": {}})
print(recv())
send({"type": "request", "command": "setBreakpoints",
"arguments": {"source": {"path": sys.argv[1]},
"breakpoints": [{"line": int(sys.argv[2])}]}})
print(recv())
send({"type": "request", "command": "configurationDone"})
# ... loop reading events and sending continue/stepIn/etc.

这适用于一次性自动化任务,但作为交互式用户体验则非常痛苦。

选项 2:从 VS Code / Cursor / Zed 附加 — 如果用户已打开其中一个编辑器,他们可以添加一个 launch.json

{
"name": "Attach to Hermes",
"type": "debugpy",
"request": "attach",
"connect": { "host": "127.0.0.1", "port": 5678 },
"justMyCode": false,
"pathMappings": [
{ "localRoot": "${workspaceFolder}", "remoteRoot": "/home/bb/hermes-agent" }
]
}

选项 3:放弃 DAP,使用 remote-pdb — 这通常才是你从终端代理真正想要的:

pip install remote-pdb

在你的代码中:

from remote_pdb import set_trace
set_trace(host="127.0.0.1", port=4444) # blocks until connection

然后从终端执行:

nc 127.0.0.1 4444
# You get a (Pdb) prompt exactly as if debugging locally.

debugpy 的 DAP 协议过于繁重时,remote-pdb 是对代理最友好的简洁选择。仅在确实需要 IDE 集成时才使用 debugpy

调试 Hermes 特定进程

测试

参见食谱 3。始终添加 -p no:xdist 或在没有 xdist 的情况下运行单个测试。

run_agent.py / CLI — 一次性执行

最简单的方法:在可疑行附近添加 breakpoint(),然后正常运行 hermes。控制权将在暂停点返回到你的终端。

tui_gateway 子进程(由 hermes --tui 生成)

网关作为 Node TUI 的子进程运行。选项如下:

A. 源码编辑网关:

# tui_gateway/server.py near the top of serve()
import debugpy
debugpy.listen(("127.0.0.1", 5678))
debugpy.wait_for_client()

启动 hermes --tui。TUI 将显示为冻结状态(其后端正在等待)。附加客户端;当你执行 continue 时,执行将继续。

B. 在特定处理程序中使用 remote-pdb

from remote_pdb import set_trace
set_trace(host="127.0.0.1", port=4444) # in the RPC handler you want to trap

从 TUI 触发匹配的斜杠命令,然后在另一个终端中执行 nc 127.0.0.1 4444

_SlashWorker 子进程

模式相同 — 在工作进程的 exec 路径中使用带有 set_trace()remote-pdb。工作进程在斜杠命令之间是持久存在的,因此第一次触发会阻塞直到你连接;后续的斜杠命令将正常通过,除非你重新武装断点。

网关(gateway/run.py

长期运行。在处理程序中使用 remote-pdb,或者如果你反正要重启网关,可以使用带有 --wait-for-clientdebugpy

常见陷阱

  1. pytest-xdist 下的 pdb 静默无效。 你不会看到提示符,测试只会挂起。始终使用 -p no:xdist-n 0

  2. CI / 非 TTY 上下文中的 breakpoint() 会挂起进程。 本地使用是安全的;切勿提交包含它的代码。添加 pre-commit grep 作为安全措施。

  3. PYTHONBREAKPOINT=0 会禁用所有 breakpoint() 调用。如果你的断点未命中,请检查环境变量:

    echo $PYTHONBREAKPOINT
  4. 仅当你同时调用 wait_for_client() 时,debugpy.listen 才会阻塞。 如果没有它,执行将继续,你的第一个断点可能在客户端附加之前就已触发。

  5. 在 hardened 内核上附加到 PID 会失败。 ptrace_scope=1(Ubuntu 默认值)仅允许对子进程进行同用户 ptrace。变通方法:echo 0 > /proc/sys/kernel/yama/ptrace_scope(需要 root 权限)或从一开始就在 debugpy 下启动。

  6. 线程。 pdb 仅调试当前线程。对于多线程代码,使用 debugpy(感知线程的 DAP)或为每个线程设置 threading.settrace()

  7. asyncio。 pdb 可以在协程中工作,但在 pdb 内部使用 await 需要 Python 3.13+,或在较旧版本中使用 interact 模式下的 await。对于 3.11/3.12,使用 asyncio.run_coroutine_threadsafe 技巧或通过 asyncio.ensure_future 使用基于 !stmt 的 await。

  8. scripts/run_tests.sh 会剥离凭据并设置 HOME=<tmpdir> 如果你的 bug 依赖于用户配置或真实的 API 密钥,它在包装器下无法复现。首先使用原始 pytest 进行调试以复现问题,然后在包装器下再次确认。

  9. Forking / 多进程。 pdb 不跟随 fork。每个子进程都需要自己的 breakpoint()set_trace()。对于 Hermes 子代理,一次调试一个进程。

验证清单

  • pip install debugpy 后,确认:python -c "import debugpy; print(debugpy.__version__)"
  • 对于远程调试,确认端口确实在监听:ss -tlnp | grep 5678
  • 第一个断点确实命中(如果未命中,你可能设置了 PYTHONBREAKPOINT=0,处于 xdist 模式下,或者在附加之前执行已结束)
  • where / w 显示预期的调用栈
  • 调试后清理:提交的代码中没有遗留的 breakpoint() / set_trace()
    rg -n 'breakpoint\(\)|set_trace\(|debugpy\.listen' --type py

一次性食谱

“为什么这个字典缺少一个键?”

# add above the KeyError site
breakpoint()
# then in pdb:
(Pdb) pp d
(Pdb) pp list(d.keys())
(Pdb) w # how did we get here

“此测试在孤立运行时通过,但在套件中失败。”

scripts/run_tests.sh tests/the_test.py --pdb -p no:xdist
# But if it only fails WITH other tests:
source .venv/bin/activate
python -m pytest tests/ -x --pdb -p no:xdist
# Now it pdb-traps at the exact failing test after state accumulated.

“我的异步处理程序死锁。”

# Add at handler entry
import remote_pdb; remote_pdb.set_trace(host="127.0.0.1", port=4444)

触发处理程序。执行 nc 127.0.0.1 4444,然后使用 w 查看挂起的帧,使用 !import asyncio; asyncio.all_tasks() 查看其他待处理的任务。

“Ink 子进程/子进程中崩溃的事后分析。”

PYTHONFAULTHANDLER=1 python -m pdb -c continue path/to/entrypoint.py
# On crash, pdb lands at the frame of the exception with full locals