For Python 3.5+:
So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException
for it (just replace ex
with your exception):
print("".join(traceback.TracebackException.from_exception(ex).format())
An extended example and other features to do this:
import traceback
try:
1/0
except Exception as ex:
print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!
print("".join(traceback.TracebackException.from_exception(ex).format()))
The output will be something like this:
True
Traceback (most recent call last):
File "untidsfsdfsdftled.py", line 29, in <module>
1/0
ZeroDivisionError: division by zero