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

前端 未结 11 1982
旧巷少年郎
旧巷少年郎 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

    If your goal is to make the exception and stacktrace message look exactly like when python throws an error, the following works in both python 2+3:

    import sys, traceback
    
    
    def format_stacktrace():
        parts = ["Traceback (most recent call last):\n"]
        parts.extend(traceback.format_stack(limit=25)[:-2])
        parts.extend(traceback.format_exception(*sys.exc_info())[1:])
        return "".join(parts)
    
    # EXAMPLE BELOW...
    
    def a():
        b()
    
    
    def b():
        c()
    
    
    def c():
        d()
    
    
    def d():
        assert False, "Noooh don't do it."
    
    
    print("THIS IS THE FORMATTED STRING")
    print("============================\n")
    
    try:
        a()
    except:
        stacktrace = format_stacktrace()
        print(stacktrace)
    
    print("THIS IS HOW PYTHON DOES IT")
    print("==========================\n")
    a()
    

    It works by removing the last format_stacktrace() call from the stack and joining the rest. When run, the example above gives the following output:

    THIS IS THE FORMATTED STRING
    ============================
    
    Traceback (most recent call last):
      File "test.py", line 31, in 
        a()
      File "test.py", line 12, in a
        b()
      File "test.py", line 16, in b
        c()
      File "test.py", line 20, in c
        d()
      File "test.py", line 24, in d
        assert False, "Noooh don't do it."
    AssertionError: Noooh don't do it.
    
    THIS IS HOW PYTHON DOES IT
    ==========================
    
    Traceback (most recent call last):
      File "test.py", line 38, in 
        a()
      File "test.py", line 12, in a
        b()
      File "test.py", line 16, in b
        c()
      File "test.py", line 20, in c
        d()
      File "test.py", line 24, in d
        assert False, "Noooh don't do it."
    AssertionError: Noooh don't do it.
    

提交回复
热议问题