pdb
包—python debuggerPython also includes a debugger to step through code. It is found in a module named pdb
. This library is modeled after the gdb
library for C. To drop into the debugger at any point in a Python program, insert the code:
Python还包括一个调试器,用于单步执行代码。它在一个名为pdb
的模块中找到。这个库是仿照C语言的`gdb‘库的。要在一个Python程序中的任意位置放入调试器,请插入以下代码:
import pdb; pdb.set_trace()
These are two statements here, but I typically type them in a single line separated by a semicolon—that way I can easily remove them with a single keystroke from my editor when I am done debugging. This is also about the only place I use a semicolon in Python code (two statements in a single line).
这里有两个语句,但我通常在一行中键入它们,用分号分隔-这样,当我完成调试时,只需从我的编辑器中按一下键就可以轻松地删除它们。这也是我在Python代码中使用分号的唯一位置(一行有两个语句)。
When this line is executed, it will present a (pdb)
prompt, which is similar to the REPL. Code can be evaluated at this prompt and you can inspect objects and variables as well. Also, breakpoints can be set for further inspection.
执行此行时,会出现(Pdb)
提示,类似于REPL。可以在此提示符下计算代码,还可以检查对象和变量。此外,还可以设置断点以供进一步检查。
Below is a table listing useful pdb
commands:
下表列出了有用的pdb
命令:
Command | Purpose |
---|---|
h , help | List the commands available 列出可用的命令 |
n , next | Execute the next line 执行下一行 |
c , cont , continue | Continue execution until a breakpoint is hit 继续执行,直到命中断点 |
w , where , bt | Print a stack trace showing where execution is打印堆栈跟踪,显示执行的位置 |
u , up | Pop up a level in the stack 在堆栈中弹出一个级别 |
d , down | Push down a level in the stack 向下推入堆栈中的一个级别 |
l , list | List source code around current line |
Note注释
In Programming Pearls, Jon Bentley states: 在《编程珍珠》一书中,乔恩·本特利表示:
When I have to debug a little algorithm deep inside a big program, I sometimes use debugging tools… though, print statements are usually faster to implement and more effective than sophisticated debuggers.
当我必须在大程序内部调试一个小算法时,我有时会使用调试工具……。
不过,与复杂的调试器相比,print语句的实现速度通常更快,效率也更高。
I’ve heard Guido van Rossum, the creator of Python, voice the same opinion: he prefers print debugging. Print debugging is easy, simply insert print
functions to provide clarity as to what is going on. This is often sufficient to figure out a problem. Make sure to remove these debug statements or change them to logging
statements before releasing the code. If more exploration is required, you can always use the pdb
module.
我听过Python的创建者Guido van Rossum表达了同样的观点:他更喜欢“打印调试”。打印调试很容易,只需插入print
函数即可清楚地了解正在发生的情况。这通常足以解决一个问题。在发布代码之前,请确保移除这些调试语句或将其更改为logging
语句。如果需要更多的探索,您可以随时使用pdb
模块。
example举例:
# Fibonacci series up to n
import pdb; pdb.set_trace()
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)