手动创建Python回溯

手动创建Python回溯,python,exception,python-2.x,traceback,Python,Exception,Python 2.x,Traceback,是否可以在Python中创建自定义回溯?我正试图编写一个函数raise\u from(),它模仿Python3的raise。。。从… def raise_from(exc, cause): """ Raises the Exception *exc* from the calling stack-frame, settings its ``__cause__`` to *cause*. """ exc.__cause__ = cause try: raise

是否可以在Python中创建自定义回溯?我正试图编写一个函数
raise\u from()
,它模仿Python3的
raise。。。从…

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

不幸的是,
回溯
实例的属性是只读的。

不必修改异常的原始对象实例,只需使用回溯对象的格式函数将其转换为更简单的格式,如列表。定制回溯列表后,将其转换回原始字符串一样的可打印字符串:
所以,您只需要将定制版本的跟踪打印回所需的文件(包括stdout,…)


但是,如果要覆盖回溯对象的原始属性,则应通过自定义插槽或重写类的@property字段来覆盖回溯对象。

我不想输出回溯,我想用特定的回溯引发异常。该例外情况仍可能被捕获,而不会打印出来。
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