【问题标题】:Manually create Python Traceback手动创建 Python Traceback
【发布时间】:2014-07-29 07:22:33
【问题描述】:

是否可以在 Python 中创建自定义回溯?我正在尝试编写一个模仿 Python 3 的 raise ... from ... 的函数 raise_from()

def raise_from(exc, cause):
    """ Raises the Exception *exc* from the calling stack-frame,
    settings its ``__cause__`` to *cause*. """

    exc.__cause__ = cause

    try: raise Exception
    except Exception:
        tb = sys.exc_info()[2]

    # Remove the last traceback entry.
    prelast_tb = tb
    while prelast_tb.tb_next:
        prelast_tb = prelast_tb.tb_next
    prelast_tb.tb_next = None

    raise type(exc), exc, tb

很遗憾,traceback 实例的属性是只读的。

【问题讨论】:

    标签: python exception python-2.x traceback


    【解决方案1】:

    您可以简单地使用追溯对象的格式函数将其转换为更简单的格式,如列表,而不是修改原始对象实例。并在自定义追溯列表后,将其转换回原始字符串一样的可打印字符串:
    因此,您只想将自定义版本的回溯打印到所需文件(包括标准输出、...)

    tb_list = traceback.extract_tb(tb)
    tb_list = tb_list[:-1] #omitting the last trace-back entry
    tb_str = tb.format_list(tb_list)
    # print whatever
    

    但是如果你想覆盖traceback对象的原始属性,你应该通过自定义slots或者覆盖class的@property字段来覆盖TraceBack对象。

    【讨论】:

    • 我不想输出回溯,我想用特定的回溯引发异常。该异常仍然可以被捕获而不被打印。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2020-05-05
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多