I want to catch and log exceptions without exiting, e.g.,
try:
do_stuff()
except Exception, err:
print(Exception, err)
# I want to print the entir
traceback.format_exception
If you only have the exception object, you can get the traceback as a string from any point of the code in Python 3 with:
import traceback
''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
Full example:
#!/usr/bin/env python3
import traceback
def f():
g()
def g():
raise Exception('asdf')
try:
g()
except Exception as e:
exc = e
tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
print(tb_str)
Output:
Traceback (most recent call last):
File "./main.py", line 12, in
g()
File "./main.py", line 9, in g
raise Exception('asdf')
Exception: asdf
Documentation: https://docs.python.org/3.7/library/traceback.html#traceback.format_exception
See also: Extract traceback info from an exception object
Tested in Python 3.7.3.