调试python程序的方法

pdb包
Python 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:

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).

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.

Below is a table listing useful pdb commands:

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

IDLE运行如以下代码,使用命令h,n,c,w,u,d,l来调试程序

# 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)