Python堆栈信息

Python堆栈信息

一. traceback模块/对象

1. 官方文档描述

This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.

概述

  1. 提取
  2. 格式化
  3. 打印

The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from ***sys.exc_info()***.

概述

  1. traceback模块会用到存储在sys.last_traceback变量中的traceback对象
  2. 该traceback对象由sys.exc_info()返回

2. 提取堆栈信息

import traceback as tb
import sys


def demo03():
    try:
        demo02()
    except:
        info = sys.exc_info()
        tb_obj = info[-1]  # traceback对象
        ss_obj = tb.extract_tb(tb_obj)  # StackSummary对象
        for fs_obj in ss_obj:  # FrameSummary对象
            print(f'文件名: {fs_obj.filename}\n 行号: {fs_obj.lineno}\n 名称: {fs_obj.name}\n 行: {fs_obj.line}', end=f'\n{"-"*30}\n')


def demo02():
    demo01()


def demo01():
    m = 3 / 0


if __name__ == '__main__':
    demo03()

输出

文件名: C:/000/workspace/python/PyCharm/learnPython/work/walnut/test/demo09.py
 行号: 7
 名称: demo03
 行: demo02()
------------------------------
文件名: C:/000/workspace/python/PyCharm/learnPython/work/walnut/test/demo09.py
 行号: 17
 名称: demo02
 行: demo01()
------------------------------
文件名: C:/000/workspace/python/PyCharm/learnPython/work/walnut/test/demo09.py
 行号: 21
 名称: demo01
 行: m = 3 / 0
------------------------------

遗留: 待完善总结异常/错误

参考: https://blog.csdn.net/shirley_sweet/article/details/77258864

你可能感兴趣的:(Python)