如何以编程方式检查 Python 中异常的堆栈跟踪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2359248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you programmatically inspect the stack trace of an exception in Python?
提问by Nick Retallack
When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I've looked at the tracebackmodule, but I can't figure out how to use it.
当Python发生异常时,你能检查堆栈吗?你能确定它的深度吗?我看过回溯模块,但我不知道如何使用它。
My goal is to catch any exceptions that occur during the parsing of an eval expression, without catching exceptions thrown by any functions it may have called. Don't berate me for using eval. It wasn't my decision.
我的目标是捕获在解析 eval 表达式期间发生的任何异常,而不捕获它可能调用的任何函数抛出的异常。不要因为我使用 eval 而责备我。这不是我的决定。
NOTE: I want to do this programmatically, not interactively.
注意:我想以编程方式而不是交互方式执行此操作。
采纳答案by AndiDog
You can use the inspectmodule which has some utility functions for tracing. Have a look at the overview of propertiesof the frame objects.
回答by Dmitry Kochkin
traceback
is enough - and I suppose that documentation describes it rather well. Simplified example:
traceback
就足够了 - 我想文档很好地描述了它。简化示例:
import sys
import traceback
try:
eval('a')
except NameError:
traceback.print_exc(file=sys.stdout)
回答by ajon
I like the traceback module.
我喜欢回溯模块。
You can get a traceback object using sys.exc_info()
. Then you can use that object to get a list preprocessed list of traceback entries using traceback.extract_tb()
. Then you can get a readable list using traceback.format_list()
as follows:
您可以使用sys.exc_info()
. 然后,您可以使用该对象来获取使用traceback.extract_tb()
. 然后您可以使用traceback.format_list()
以下方法获得可读列表:
import sys
import traceback, inspect
try:
f = open("nonExistant file",'r')
except:
(exc_type, exc_value, exc_traceback) = sys.exc_info()
#print exception type
print exc_type
tb_list = traceback.extract_tb(sys.exc_info()[2])
tb_list = traceback.format_list(tb_list)
for elt in tb_list:
print elt
#Do any processing you need here.
See the sys Module: http://docs.python.org/library/sys.html
查看 sys 模块:http: //docs.python.org/library/sys.html
and the traceback Module: http://docs.python.org/library/traceback.html
回答by alinsoar
You define such a function (doc here):
您定义了这样一个函数(此处为 doc):
def raiseErr():
for f in inspect.stack(): print '-', inspect.getframeinfo(f[0])
and call it from your modules so:
并从您的模块中调用它,以便:
raiseErr()
The function raiseErrwill print info about the place you called it.
函数raiseErr将打印有关您调用它的地方的信息。
More elaborate, you can do so:
更详细地说,你可以这样做:
import inspect, traceback
A = [inspect.getframeinfo(f[0]) for f in inspect.stack()]
print "traceback structure fields:", filter(lambda s: s[0] != '_', dir(A[0]))
print A[0].filename, A[0].lineno
for f in inspect.stack():
F = inspect.getframeinfo(f[0])
print '-', F.filename, F.lineno, '\t', F.code_context[0].strip()
Other possibility is to define this function:
另一种可能性是定义这个函数:
def tr():
print '* - '*10,
print sys._getframe(1).f_code.co_name
And call it in the place where you want the trace. If you want all the trace, make an iterator from 1 up in _getframe(1)
.
并在您想要跟踪的地方调用它。如果您想要所有跟踪,请在_getframe(1)
.
回答by Peter Hansen
In addition to AndiDog's answer about inspect
, note that pdb
lets you navigate up and down the stack, inspecting locals and such things. The source in the standard library pdb.py
could be helpful to you in learning how to do such things.
除了 AndiDog 的回答 about 之外inspect
,请注意,它pdb
可以让您在堆栈中上下导航,检查本地人等。标准库中的源代码pdb.py
可以帮助您学习如何做这些事情。