The module
pdbdefines an interactive source code debugger for Python programs. it is actually defined as the classPdb. The debugger’s prompt is(Pdb).
pdb 既可以作为 package 内嵌到python脚本里,也可以作为python脚本来调试其他python脚本。
- 作为package 内嵌到脚本中调试
import pdbpdb.set_trace() # set a break point hereimport mymodulepdb.run('mymodule.test()') # debug mymodule.test() method
作为脚本内嵌代码的调试方法参考:pdb — The Python Debugger
- 作为python脚本调试其他python脚本
pdb 作为脚本内嵌代码将脚本至于静态调试模式,后面要 release 代码的时候得一条条删除调试代码,很麻烦,不及将 pdb 作为脚本使用来得方便。
python -m pdb test.py # debug test.py script
上述脚本将进入交互式调试环境,在该环境下,通过以下命令完成调试任务:
| Command | Short form | What it does |
|---|---|---|
args |
a |
Print the argument list of the current function |
break |
b |
Creates a breakpoint (requires parameters) in the program execution |
continue |
c or cont |
Continues program execution |
help |
h |
Provides list of commands or help for a specified command |
jump |
j |
Set the next line to be executed |
list |
l |
Print the source code around the current line |
next |
n |
Continue execution until the next line in the current function is reached or returns |
step |
s |
Execute the current line, stopping at first possible occasion |
pp |
pp |
Pretty-prints the value of the expression |
quit or exit |
q |
Aborts the program |
return |
r |
Continue execution until the current function returns |
更多快捷命令参考:pdb — The Python Debugger
结合代码编辑器里显示的行号等信息,方便地在指定行设断点,执行到断点,执行下一行,进入子函数等。
如果调试的python脚本出现未知错误终止了,我们还可以结合 gdb 命令打印调用栈,确定出错的位置。
gdb python(gdb) run test.py# 假设上述脚本在没有抛出异常的情况下非正常终止(gdb) bt # 查看调用栈
