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.
For those using Python-3
Using traceback module and exception.__traceback__ one can extract the stack-trace as follows:
traceback.extract_stack()__traceback__ from the exception object using traceback.extract_tb()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