繁体   English   中英

手动创建Python Traceback

[英]Manually create Python Traceback

是否可以在Python中创建自定义回溯? 我正在尝试编写一个函数raise_from() ,它模仿Python 3的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实例的属性是只读的。

您可以简单地使用跟踪对象的格式函数将其转换为更简单的格式(如list),而不是修改异常的原始对象实例。 在自定义回溯列表后,将其转换回原始的可打印字符串:
所以,你只想将自定义版本的trace-back打印到所需的文件中(包括stdout,...)

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对象的原始属性,则应通过自定义插槽或覆盖类的@property字段来覆盖TraceBack对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM