pdb
import pdb; pdb.set_trace()
(Pdb)
在最近刚发布的 Python 3.7 中,引入了 PPE 553 新特性 beakpoint ( Python 3.7 的新特性可以参考这里:https://docs.python.org/3/whatsnew/3.7.html ),现在可以通过直接在脚本中调用
breakpoint()
来调试。默认情况下,breakpoint() 会 import pdb 并调用 pdb.set_trace(),如上所示。 但是,使用breakpoint()更灵活,允许您通过其API控制调试行为并使用环境变量 PYTHONBREAKPOINT。 例如,在环境中设置PYTHONBREAKPOINT = 0将完全禁用 breakpoint() ,从而禁用调试。 如果您使用的是Python 3.7或更高版本,建议使用breakpoint()而不是pdb.set_trace()。
python3 -m pdb app.py arg1 arg2
也可以通过直接传入 -m pdb 的方式进行调试
比较常用的操作是 b linenumber 加断点,c 跳过当前断点,s step in 当前断点,dir 查看当前结构体的属性等
gdb
还有一种经常遇到的情况就是 python 遇到 segment fault ,如果你的 codes 里使用了 c 的 module ,则可以使用 gdb 进行调试。
gdb python
run /path/to/your/script.py
这时程序会不停的打印类似于
[New Thread 0x7fffc8ff9700 (LWP 32104)]
[Thread 0x7fffc8ff9700 (LWP 32104) exited]
的信息,这个可以通过
(gdb) set print thread-events off
另外一种可行的方式是,使用 faulthandler:
First add the following to the top of your module.
import faulthandler; faulthandler.enable()
Then re-run your program with the faulthandler startup flag.
Passed as an argument.
# pass as an argument
python -Xfaulthandler my_program.py
# Or as an environment variable.
PYTHONFAULTHANDLER=1 python my_program.py