可以在Python中创建自定义回溯吗?我正在尝试编写一个模仿Python3的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实例的属性是只读的。
发布于 2014-06-09 06:02:06
您可以简单地使用回溯对象的格式函数将其转换为更简单的格式,而不是修改exception的原始对象实例。在自定义回溯列表后,将其转换回可打印的字符串,如原来的字符串:
因此,您只需要将自定义版本的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但是如果你想覆盖回溯对象的原始属性,你应该通过定制插槽或者覆盖类的@property字段来覆盖traceback对象。
https://stackoverflow.com/questions/24108656
复制相似问题