随笔-PYTHON-打印错误堆栈

import sys
import traceback

def print_traceback():
    '打印通常的回溯信息,且附有每帧中的局部变量的列表'
    tb=sys.exc_info()[2]    #返回当前异常的(type,value,traceback)
    while tb.tb_next:
        tb=tb.tb_next    #栈中的下一个traceback对象
    stack=[]
    f=tb.tb_frame #每个traceback对应一个帧
    while f:
        stack.append(f) #stack存放指向帧对象的所有引用
        f=f.f_back
    stack.reverse()
    traceback.print_exc()
    log("ERROR", 'locals by frame,innermost last')
    for frame in stack:
        log("ERROR", '  Frame %s in %s at line %s'%(frame.f_code.co_name,
                                           frame.f_code.co_filename,
                                           frame.f_lineno))
        [ log("ERROR", '    {}:{}'.format(key, value)) for key,value in frame.f_locals.items() ]
posted @ 2023-07-13 11:11  LiYanbin  阅读(109)  评论(0编辑  收藏  举报