本文介绍了如何将traceback / sys.exc_info()值保存在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将错误名称和追溯详细信息保存到变量中。这是我的尝试。
I want to save the name of the error and the traceback details into a variable. Here's is my attempt.
import sys
try:
try:
print x
except Exception, ex:
raise NameError
except Exception, er:
print "0", sys.exc_info()[0]
print "1", sys.exc_info()[1]
print "2", sys.exc_info()[2]
输出:
0 <type 'exceptions.NameError'>
1
2 <traceback object at 0xbd5fc8>
所需产出
0 NameError
1
2 Traceback (most recent call last):
File "exception.py", line 6, in <module>
raise NameError
我知道这可以很容易地使用追溯模块,但我想知道sys.exc_info()[2]对象的用法。
P.S. I know this can be done easily using the traceback module, but I want to know usage of sys.exc_info()[2] object here.
推荐答案
这是我如何做的:
>>> import traceback
>>> try:
... int('k')
... except:
... var = traceback.format_exc()
...
>>> print var
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'
不过请查看,因为您可能会找到更合适的方法,具体取决于您想要的方式稍后处理您的变量...
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...
这篇关于如何将traceback / sys.exc_info()值保存在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!