在python中,如何使用traceback将错误消息分配给变量?

问题描述 投票:0回答:2
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()来打印输出。相反,我想将输出保存到变量。我怎样才能做到这一点?

python exception exception-handling
2个回答
3
投票

使用traceback.format_exc()

import traceback

try:
   1/0
except Exception:
   trace = traceback.format_exc()
   print trace

来自Python documentation

traceback.format_exc([极限])

这与print_exc(limit)类似,但返回一个字符串而不是打印到文件。


0
投票

试试这个:

import traceback  
try:  
   1/0  
except Exception as e:  
   error = traceback.format_exc()


print(error)
© www.soinside.com 2019 - 2024. All rights reserved.