python debug 调试

发布时间 2023-07-15 00:37:33作者: 绣幕

python debug调试

pdb

2种调试方法

  1. 在程序中设置断点
# test_pdb.py 
import pdb

t = [1,2]
pdb.set_trace()

程序运行到 pdb.set_trace()时会中断,此时可以通过pdb查看上下文变量`

# /bin/python test_pdb.py 
--Return--
> test_pdb.py(4)<module>()->None
-> pdb.set_trace()
(Pdb) l
  1     import pdb
  2  
  3     t = [1,2]
  4  -> pdb.set_trace()
[EOF]
(Pdb) p t
[1, 2]
(Pdb) 
  1. -i 运行.python文件
# test_pdb.py
t = [1,2]
print(t[99])

执行 python3 -i test_pdb.py
如下:

# python3 -i test_pdb.py 
Traceback (most recent call last):
  File "test_pdb.py", line 4, in <module>
    print(t[99])
IndexError: list index out of range
>>> import pdb
>>> pdb.pm()
> test_pdb.py(4)<module>()
-> print(t[99])
(Pdb) l
  1     import pdb
  2  
  3     t = [1,2]
  4  -> print(t[99])
  5  
[EOF]
(Pdb) p t
[1, 2]
(Pdb) p len(t)
2
(Pdb) 

需要注意的点

-i 运行调试必须是程序发生异常时,才能进行 pdb 调试。如果自身设置了异常捕获,此时进行pdb调试会发生异常。
详见:https://bugs.python.org/issue39208

示例如下:

import traceback

try:
  t = [1,2]
  print(t[99])
except Exception as e:
  print(traceback.format_exc())

执行 python -i test_pdb.py

# /bin/python -i test_pdb.py 
Traceback (most recent call last):
  File "test_pdb.py", line 5, in <module>
    print(t[99])
IndexError: list index out of range

>>> import pdb
>>> pdb.pm()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/pdb.py", line 1604, in pm
    post_mortem(sys.last_traceback)
AttributeError: module 'sys' has no attribute 'last_traceback'