How can I modify a Python traceback object when raising an exception?

后端 未结 7 1320
梦如初夏
梦如初夏 2020-11-29 09:56

I\'m working on a Python library used by third-party developers to write extensions for our core application.

I\'d like to know if it\'s possible to modify the trace

7条回答
  •  生来不讨喜
    2020-11-29 10:28

    This code might be of interest for you.

    It takes a traceback and removes the first file, which should not be shown. Then it simulates the Python behavior:

    Traceback (most recent call last):
    

    will only be shown if the traceback contains more than one file. This looks exactly as if my extra frame was not there.

    Here my code, assuming there is a string text:

    try:
        exec(text)
    except:
        # we want to format the exception as if no frame was on top.
        exp, val, tb = sys.exc_info()
        listing = traceback.format_exception(exp, val, tb)
        # remove the entry for the first frame
        del listing[1]
        files = [line for line in listing if line.startswith("  File")]
        if len(files) == 1:
            # only one file, remove the header.
            del listing[0]
        print("".join(listing), file=sys.stderr)
        sys.exit(1)
    

提交回复
热议问题