「Python」- 常用调试方法汇总

问题描述

在调试代码或者学习新框架时,我们需要通过调试的方式,以追踪代码的执行路径。毕竟,我们不能指望每种框架、每个应用都有相关的说明文档,来让我们学习。所以,我们需要掌握常用的调试方法,用于代码调试、框架学习、追踪执行路径。

该笔记将记录:在 Python 中,常用的调试方法、代码执行路径追踪等等方法,以及常见问题处理。

解决方案

通过 traceback.print_stack() 追踪

import traceback
traceback.print_stack()

通过 sys.setprofile(tracefunc) 追踪

def tracefunc(frame, event, arg, indent=[0]):
    if event == "call":
        indent[0] += 2
        print("-" * indent[0] + "> call function", frame.f_code.co_name)
    elif event == "return":
        print("<" + "-" * indent[0], "exit function", frame.f_code.co_name)
        indent[0] -= 2
    return tracefunc

import sys
sys.setprofile(tracefunc)

# sys.settrace(tracefunc)  # settrace() 的粒度更细,比如在每行调用时,将执行 tracefunc 函数

通过 trace 模块

python -m trace --listfuncs foo.py  # 但是,只会显示一次,而且是在执行结束后。

python -m trace --trace foo.py  # 在执行的过程中,显示函数调用

python -m trace --trackcalls foo.py  # 显示每一行

参考文献

traceback — Print or retrieve a stack traceback — Python 3.9.2 documentation
debugging – print python stack trace without exception being raised – Stack Overflow
sys — System-specific parameters and functions — Python 3.9.2 documentation
python – How do I print functions as they are called – Stack Overflow