捕获异常时,如何获取前一帧的类型、文件和行号?

2024-05-17 11:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

this question开始,我正在向下一级执行错误处理。也就是说,我调用一个调用另一个更大函数的函数,我想知道它在那个大函数中失败的地方,而不是在较小的函数中。具体示例。代码是:

import sys, os

def workerFunc():
    return 4/0

def runTest():
    try:
        print workerFunc()
    except:
        ty,val,tb = sys.exc_info()
        print "Error: %s,%s,%s" % (
            ty.__name__,
            os.path.split(tb.tb_frame.f_code.co_filename)[1],
            tb.tb_lineno)

runTest()

输出为:

^{pr2}$

但是第8行是“print workerFunc()”—我知道那行失败了,但我希望在前面有一行:

Error: ZeroDivisionError,tmp2.py,4

Tags: 函数代码示例osdef地方syserror
3条回答

你需要找到回溯的底部,所以你需要循环直到没有更多的帧。执行此操作可找到所需的帧:

while tb.tb_next:
    tb = tb.tb_next

之后系统执行信息. 无论发生了多少次调用帧,都会找到异常。在

添加一行:

    tb = tb.tb_next

就在您呼叫sys.exc_info之后。在

请参阅“回溯对象”下的文档here。在

tb.tb_next是你的朋友:

import sys, os

def workerFunc():
    return 4/0

def runTest():
    try:
        print workerFunc()
    except:
        ty,val,tb = sys.exc_info()
        print "Error: %s,%s,%s" % (
            ty.__name__,
            os.path.split(tb.tb_frame.f_code.co_filename)[1],
            tb.tb_next.tb_lineno)

runTest()

但是traceback module可以做到这一点,还有更多:

^{pr2}$

相关问题 更多 >