pdb — The Python Debugger

一段簡單的程式碼

print(f'file = {__file__}')

常見pdb幾種使用方式

1. 直接使用

python -m pdb file.py

執行上面指令會讓整個檔案進入pdb模式操作

( P / d h f b o i ) m l e e / s = r c / _ t f e i s l t e . _ p _ y ( 1 ) < m o d u l e > ( )

2. 設斷點

把上面程式碼改成

file = __file__
import pdb; pdb.set_trace()
print(f'file = {file}')

執行後則會在第二行進入pdb

( P / d h p b o r ) m i e n / t s ( r f c ' f t i e l s e t . = p y { ( f 3 i ) l < e m } o ' d ) u l e > ( )

結果如同上方,此時進入操作。

在python3.7之後版本,可以使用 breakpoint() 指令

詳見pep553

file = __file__
breakpoint()
print(f'file = {file}')

3. python shell 中使用

如果使用中遇到一些function的錯誤,可以這樣使用

創造一個測試function:

def test():
    a = 1
    b = 'b'
    return a + b

這個function會出現錯誤:數字和字串的操作

再進入python

>>> from test import test
>>> import pdb
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/src/test.py", line 4, in test
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> pdb.pm()
> /home/src/test.py(4)test()
-> return a + b
(Pdb)

一樣也會進入pdb操作

結語

上面提供了python debug的幾個方式,

可以加速我們遇到困難時的解決方法,

並且不要用print找錯誤

再來就是要習慣常用的快捷鍵操作~