Get exception description and stack trace which caused an exception, all as a string

前端 未结 11 1978
旧巷少年郎
旧巷少年郎 2020-11-30 16:22

I\'ve seen a lot of posts about stack trace and exceptions in Python. But haven\'t found what I need.

I have a chunk of Python 2.7 code that may raise an exception.

11条回答
  •  鱼传尺愫
    2020-11-30 16:45

    For those using Python-3

    Using traceback module and exception.__traceback__ one can extract the stack-trace as follows:

    • grab the current stack-trace using traceback.extract_stack()
    • remove the last three elements (as those are entries in the stack that got me to my debug function)
    • append the __traceback__ from the exception object using traceback.extract_tb()
    • format the whole thing using traceback.format_list()
    import traceback
    def exception_to_string(excp):
       stack = traceback.extract_stack()[:-3] + traceback.extract_tb(excp.__traceback__)  # add limit=?? 
       pretty = traceback.format_list(stack)
       return ''.join(pretty) + '\n  {} {}'.format(excp.__class__,excp)
    

    A simple demonstration:

    def foo():
        try:
            something_invalid()
        except Exception as e:
            print(exception_to_string(e))
    
    def bar():
        return foo()
    

    We get the following output when we call bar():

      File "./test.py", line 57, in 
        bar()
      File "./test.py", line 55, in bar
        return foo()
      File "./test.py", line 50, in foo
        something_invalid()
    
       name 'something_invalid' is not defined
    

提交回复
热议问题