Manually create Python Traceback

Is it possible to create my own trace in Python? I am trying to write a function raise_from()that mimics 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

Unfortunately, instance attributes tracebackare read-only.

+4
source share
1 answer

, , back-back, , 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 .

+1

Source: https://habr.com/ru/post/1543765/


All Articles