本文介绍了如何在变量中保存回溯/sys.exc_info() 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将错误名称和回溯详细信息保存到一个变量中.这是我的尝试.
导入系统尝试:尝试:打印 x除了例外,例如:引发 NameError除了例外,呃:打印0",sys.exc_info()[0]打印1",sys.exc_info()[1]打印2",sys.exc_info()[2]
输出:
0 12 <在0xbd5fc8处的回溯对象>
期望输出:
0 NameError12 回溯(最近一次调用最后一次): 中的文件exception.py",第 6 行引发 NameError
附言我知道这可以使用回溯模块轻松完成,但我想知道这里 sys.exc_info()[2] 对象的用法.
解决方案
我是这样做的:
>>>导入回溯>>>尝试:... int('k')... 除了:... var = traceback.format_exc()...>>>打印变量回溯(最近一次调用最后一次):文件<stdin>",第 2 行,在 <module> 中ValueError:int() 的无效文字,基数为 10:'k'然而,您应该查看 traceback 文档,因为您可能会找到更合适的方法,具体取决于之后如何处理变量...
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]
Output:
0 <type 'exceptions.NameError'>
1
2 <traceback object at 0xbd5fc8>
Desired Output:
0 NameError
1
2 Traceback (most recent call last):
File "exception.py", line 6, in <module>
raise NameError
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.
解决方案
This is how I do it:
>>> 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...
这篇关于如何在变量中保存回溯/sys.exc_info() 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!