コード
import sys
import traceback
try:
0/0
except:
# print
traceback.print_exc()
# as string
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
exc = ''.join('' + line for line in lines)
出力例
Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: integer division or modulo by zero


