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.
>>> 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']