在交互環境中一般使用pdb.run來調試:python
import pdb def pdb_test(arg): for i in range(arg): print(i) return arg pdb.run("pdb_test(3)")
b 函數名、行號:函數
打斷點,b能夠查詢全部的斷點。spa
(Pdb) b pdb_test Breakpoint 1 at c:\users\plpcc\desktop\pdbtest.py:3 (Pdb) b Num Type Disp Enb Where 1 breakpoint keep yes at c:\users\plpcc\desktop\pdbtest.py:3
c:調試
運行程序,直到遇到斷點。blog
(Pdb) c > c:\users\plpcc\desktop\pdbtest.py(4)pdb_test() -> for i in range(arg):
l:cmd
查看斷點周圍的代碼string
(Pdb) l 1 import pdb 2 3 B def pdb_test(arg): 4 -> for i in range(arg): 5 print(i) 6 return arg 7 8 pdb.run("pdb_test(3)")
a:it
查看參數io
(Pdb) a arg = 3
s, n:ast
單步運行,區別s會進入路徑中的函數,n不會進入
p:
查看錶達式的值
(Pdb) p i 0
condition:
條件斷點,只有條件爲true斷點才命中
> c:\users\plpcc\desktop\pdbtest.py(5)pdb_test() -> print(i) (Pdb) l 1 import pdb 2 3 def pdb_test(arg): 4 for i in range(arg): 5 B-> print(i) 6 return arg 7 8 pdb.run("pdb_test(3)") [EOF] (Pdb) b Num Type Disp Enb Where 2 breakpoint keep yes at c:\users\plpcc\desktop\pdbtest.py:5 (Pdb) condition 2 i==1 //i==1時才觸發斷點2 New condition set for breakpoint 2. (Pdb) b Num Type Disp Enb Where 2 breakpoint keep yes at c:\users\plpcc\desktop\pdbtest.py:5 stop only if i==1 (Pdb) c 0 //i==0直接打印未斷住 > c:\users\plpcc\desktop\pdbtest.py(5)pdb_test() -> print(i) //觸發斷點,i==1 (Pdb) p i 1
bt:
查看調用堆棧
(Pdb) bt c:\python33\lib\bdb.py(405)run() -> exec(cmd, globals, locals) <string>(1)<module>() > c:\users\plpcc\desktop\pdbtest.py(5)pdb_test() -> print(i)
r:
執行到函數返回
(Pdb) r 1 2 --Return-- > c:\users\plpcc\desktop\pdbtest.py(6)pdb_test()->3 //代碼位置、函數返回值->3 -> return arg //代碼位置的語句 (Pdb) l 1 import pdb 2 3 def pdb_test(arg): 4 for i in range(arg): 5 print(i) 6 -> return arg 7 8 pdb.run("pdb_test(3)")
經過pdb.set_trace() 在代碼中指定位置嵌入一個斷點,一般能夠經過調試開關來控制
import pdb __DEBUG__ = True def pdb_test(arg): if True == __DEBUG__: pdb.set_trace() for i in range(arg): print(i) return arg pdb_test(3)
運行後在pdb.set_trace()位置被斷住,當__DEBUG__ = False,代碼正常運行
> c:\users\plpcc\desktop\pdbtest.py(8)pdb_test() -> for i in range(arg): (Pdb) l 3 __DEBUG__ = True 4 5 def pdb_test(arg): 6 if True == __DEBUG__: 7 pdb.set_trace() 8 -> for i in range(arg): 9 print(i) 10 return arg 11 12 pdb_test(3) [EOF]
經過pdb.pm()進行過後調試,能夠跟蹤異常程序最後的堆載信息:
Traceback (most recent call last): File "C:\Users\plpcc\Desktop\pdbTest.py", line 13, in <module> pdb_test(3) File "C:\Users\plpcc\Desktop\pdbTest.py", line 10, in pdb_test 1/0 ZeroDivisionError: division by zero >>> import pdb >>> pdb.pm() > c:\users\plpcc\desktop\pdbtest.py(10)pdb_test() -> 1/0 (Pdb) l 5 def pdb_test(arg): 6 if True == __DEBUG__: 7 pdb.set_trace() 8 for i in range(arg): 9 print(i) 10 -> 1/0 11 return arg 12 13 pdb_test(3)