import traceback
try:
1/0
except Exception,e:
traceback.print_exc()
输出如下:
Traceback (most recent call last):
File "test_traceback.py", line 3, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
但是我不想使用traceback.print_exc()
来打印输出。相反,我想将输出保存到变量。我怎样才能做到这一点?
使用traceback.format_exc()
:
import traceback
try:
1/0
except Exception:
trace = traceback.format_exc()
print trace
traceback.format_exc([极限])
这与print_exc(limit)类似,但返回一个字符串而不是打印到文件。
试试这个:
import traceback
try:
1/0
except Exception as e:
error = traceback.format_exc()
print(error)