使用 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