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

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

    >>> import sys
    >>> import traceback
    >>> try:
    ...   5 / 0
    ... except ZeroDivisionError as e:
    ...   type_, value_, traceback_ = sys.exc_info()
    >>> traceback.format_tb(traceback_)
    ['  File "", line 2, in \n']
    >>> value_
    ZeroDivisionError('integer division or modulo by zero',)
    >>> type_
    
    >>>
    >>> 5 / 0
    Traceback (most recent call last):
      File "", line 1, in 
    ZeroDivisionError: integer division or modulo by zero
    

    You use sys.exc_info() to collect the information and the functions in the traceback module to format it. Here are some examples for formatting it.

    The whole exception string is at:

    >>> ex = traceback.format_exception(type_, value_, traceback_)
    >>> ex
    ['Traceback (most recent call last):\n', '  File "", line 2, in \n', 'ZeroDivisionError: integer division or modulo by zero\n']
    

提交回复
热议问题