【问题标题】:Traceback Information Lost in Decorator装饰器中丢失的追溯信息
【发布时间】:2019-01-06 05:47:17
【问题描述】:

运行以下代码时,我无法从装饰器内的sys.exc_info() 提取的回溯信息中获取预期的行号。

import sys


def get_traceback(function):
    def wrapper(*args, **kwargs):
        try:
            function(*args, **kwargs) # line 7
        except:
            return sys.exc_info()[2]
    return wrapper


def inner():
    raise ValueError() # line 14 <--- the expected line number


@get_traceback
def outer():
    inner() # line 19


tb = outer()
print(tb.tb_lineno) # prints 7
print(tb.tb_next.tb_lineno) # prints 19

当在装饰器之外对sys.exc_info() 进行类似调用时,我能够获得适当的行号。这是什么原因,我该怎么做才能得到正确的行号?

提前致谢!

【问题讨论】:

    标签: python decorator traceback


    【解决方案1】:

    装饰器只是为您的回溯添加了另一个步骤。

    以下是使用traceback 内置库获取它的方法:

    import traceback
    
    tb = outer()
    
    traceback.extract_tb(tb)[-1].lineno
    

    或在以前的样式中,添加另一个tb_next

    print(tb.tb_next.tb_next.tb_lineno)
    

    【讨论】:

      【解决方案2】:

      你应该看看traceback shows up until decorator

      我在我的装饰器中尝试了它,它可以很好地打印整个内部和外部堆栈。

      【讨论】:

        猜你喜欢
        • 2012-07-25
        • 1970-01-01
        • 2011-07-03
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 2022-12-05
        相关资源
        最近更新 更多