How to get the last exception object after an error is raised at a Python prompt?

后端 未结 2 1976
半阙折子戏
半阙折子戏 2020-12-14 14:46

When debugging Python code at the interactive prompt (REPL), often I\'ll write some code which raises an exception, but I haven\'t wrapped it in a try/exc

相关标签:
2条回答
  • 2020-12-14 14:56

    The sys module provides some functions for post-hoc examining of exceptions: sys.last_type, sys.last_value, and sys.last_traceback.

    sys.last_value is the one you're looking for.

    0 讨论(0)
  • 2020-12-14 15:15

    As @Cairnarvon mentioned, I didn't find any last_valuemember is sys module.

    sys.exc_info() did the trick for me. sys.exc_info() returns a tuple with three values (type, value, traceback).

    So sys.exc_info()[1] will give the readable error. Here is the example,

    import sys
    list = [1,2,3,4]
    try:
        del list[8]
    except Exception:
        print(sys.exc_info()[1])
    

    will output list assignment index out of range

    Also, traceback.format_exc() from traceback module can be used to print out the similar information.

    Below is the output if format_exec() is used,

    Traceback (most recent call last):
      File "python", line 6, in <module>
    IndexError: list assignment index out of range
    
    0 讨论(0)
提交回复
热议问题