使用 pdb 进行 Python 调试器逐步调试

Python 标准库包括被称为交互式调试库 PDBpdb 具有广泛的功能,最常用的是逐步程序。

要立即进入逐步调试使用:

python -m pdb <my_file.py>

这将在程序的第一行启动调试器。

通常,你需要定位代码的特定部分以进行调试。为此,我们导入 pdb 库并使用 set_trace() 来中断这个有问题的示例代码的流程。

import pdb

def divide(a, b):
    pdb.set_trace()
    return a/b 
    # What's wrong with this? Hint: 2 != 3

print divide(1, 2)

运行此程序将启动交互式调试程序。

python foo.py 
> ~/scratch/foo.py(5)divide()
-> return a/b
(Pdb) 

通常此命令在一行上使用,因此可以使用单个#字符注释掉它

 import pdf; pdb.set_trace()

(Pdb) 提示符下可以输入命令。这些命令可以是调试器命令或 python。要打印变量,我们可以使用调试器中的 p 或 python 的 print

(Pdb) p a
1
(Pdb) print a
1

要查看所有局部变量的列表使用

locals

内置函数

这些是很好的调试器命令,可以知道:

b <n> | <f>: set breakpoint at line *n* or function named *f*.
# b 3
# b divide
b: show all breakpoints.
c: continue until the next breakpoint.
s: step through this line (will enter a function).
n: step over this line (jumps over a function).
r: continue until the current function returns.
l: list a window of code around this line.
p <var>: print variable named *var*.
# p x
q: quit debugger.
bt: print the traceback of the current execution call stack
up: move your scope up the function call stack to the caller of the current function
down: Move your scope back down the function call stack one level
step: Run the program until the next line of execution in the program, then return control back to the debugger
next: run the program until the next line of execution in the current function, then return control back to the debugger
return: run the program until the current function returns, then return control back to the debugger
continue: continue running the program until the next breakpoint (or set_trace si called again)

调试器还可以交互式地评估 python:

-> return a/b
(Pdb) p a+b
3
(Pdb) [ str(m) for m in [a,b]] 
['1', '2']
(Pdb) [ d for d in xrange(5)]
[0, 1, 2, 3, 4]

注意:

如果你的任何变量名称与调试器命令一致,请使用感叹号’ ‘在 var 之前显式引用变量而不是调试器命令。例如,通常可能会对计数器使用变量名c,并且你可能希望在调试器中打印它。一个简单的’ c ‘命令将继续执行直到下一个断点。而是使用’ !c ‘打印变量的值,如下所示:

(Pdb) !c
4