Manually create Python Traceback
Asked Answered
E

1

6

Is it possible to create a custom traceback in Python? I'm trying to write a function raise_from() that imitates Python 3's 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

Unfortunately, the attributes of the traceback instance are read-only.

Endpaper answered 8/6, 2014 at 17:12 Comment(0)
C
0

Instead of modifying original object instance of exception, you can simply use format functions for trace-back objects to convert it to more simpler format like list. And after customization of trace-back list, convert it back to printable string like original one:
So, you just want to print out customized version of trace-back into desired file(including 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

But if you want to overwrite original attributes of the traceback object, you should override TraceBack object by customizing slots or overriding @property fields of class.

Cutwater answered 8/6, 2014 at 22:2 Comment(1)
I do not want to output the traceback, I want to raise an exception with a specific traceback. That exception could still be caught and not printed.Endpaper

© 2022 - 2024 — McMap. All rights reserved.