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

后端 未结 7 1307
梦如初夏
梦如初夏 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:51

    For python3, here's my answer. Please read the comments for an explanation:

    def pop_exception_traceback(exception,n=1):
        #Takes an exception, mutates it, then returns it
        #Often when writing my repl, tracebacks will contain an annoying level of function calls (including the 'exec' that ran the code)
        #This function pops 'n' levels off of the stack trace generated by exception
        #For example, if print_stack_trace(exception) originally printed:
        #   Traceback (most recent call last):
        #   File "<string>", line 2, in <module>
        #   File "<string>", line 2, in f
        #   File "<string>", line 2, in g
        #   File "<string>", line 2, in h
        #   File "<string>", line 2, in j
        #   File "<string>", line 2, in k
        #Then print_stack_trace(pop_exception_traceback(exception),3) would print: 
        #   File "<string>", line 2, in <module>
        #   File "<string>", line 2, in j
        #   File "<string>", line 2, in k
        #(It popped the first 3 levels, aka f g and h off the traceback)
        for _ in range(n):
            exception.__traceback__=exception.__traceback__.tb_next
        return exception
    
    0 讨论(0)
提交回复
热议问题