调试Python程序工具(pdb, cProfile, pstats)

pdb

1
python -m pdb test.py

进入交互pdb调试界面后,可键入如下命令

命令 用法
h/help 查看可用命令
h command 查看command用法
p 查看变量值
pp 查看变量值(pretty-print)
n/next 单步执行(遇到函数会跳过中间步骤)
s/step 单步执行(遇到函数不会跳过中间步骤)
c/cont/continue 执行到下一断点前
run/restart 重新运行程序
b/break 10 第十行设置断点
cl/clear num 删除断点
l 显示当前文件的源码
ll/longlist 显示当前function或frame的源码
j/jump 10 跳到第十行开始执行(跳过某些代码)
unt/until 10 执行到第十行
a/args 当前函数参数值
q/quit/exit 退出
u/up 上层调用
d/down 下层调用
enable/disable 断点生效/失效
alias/unalias 别名/取消别名
r/return 执行到return
rv/retval 打印上次return的值

文件内调试

1
2
import pdb
pdb.set_trace()

cProfile, pstats

1
2
3
4
5
6
7
8
9
10
11
python -m cProfile -s cumtime main.py *args
python -m cProfile -o profile main.py *args

python -m pstats profile
# sort cumtime # 排序方式
# stats
# stats 2 # 前两行
# help
# callees # called
# callers # was called by
python -c "import pstats;p=pstats('profile');p.strip()_dirs().sort_stats('tottime').print_stats(10)"
name description
ncalls 调用次数
tottime 总体耗时
percall 单次耗时
cumtime 累计耗时(含有内层时间)
percall 单次耗时(含有内层时间)
filename:lineno(function) 文件名:行号(函数)