如何以编程方式检查 Python 中异常的堆栈跟踪?
当Python发生异常时,你能检查堆栈吗?你能确定它的深度吗?我查看了 traceback 模块,但我不知道如何使用它。
我的目标是捕获 eval 表达式解析期间发生的任何异常,而不捕获它可能调用的任何函数引发的异常。不要因为我使用 eval 而责备我。这不是我的决定。
注意:我想以编程方式而不是交互方式执行此操作。
When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I've looked at the traceback module, but I can't figure out how to use it.
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.
NOTE: I want to do this programmatically, not interactively.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
traceback
就足够了 - 我认为文档描述得相当好。简化示例:traceback
is enough - and I suppose that documentation describes it rather well. Simplified example:您可以使用 inspect 模块,该模块具有一些用于跟踪的实用函数。查看框架对象的属性概述。
You can use the inspect module which has some utility functions for tracing. Have a look at the overview of properties of the frame objects.
我喜欢回溯模块。
您可以使用 sys.exc_info() 获取回溯对象。然后,您可以使用该对象通过
traceback.extract_tb()
获取回溯条目的预处理列表。然后,您可以使用traceback.format_list()
获取可读列表,如下所示:请参阅 sys 模块:http://docs.python.org/library/sys.html
和回溯模块:http://docs.python.org/library/traceback.html
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 usingtraceback.extract_tb()
. Then you can get a readable list usingtraceback.format_list()
as follows:See the sys Module: http://docs.python.org/library/sys.html
and the traceback Module: http://docs.python.org/library/traceback.html
您定义这样一个函数(doc here):
并从模块中调用它:
函数raiseErr将打印有关您调用它的位置的信息。
更详细地说,您可以这样做:
另一种可能性是定义此函数:
并在您想要跟踪的地方调用它。如果您想要所有跟踪,请在
_getframe(1)
中创建一个从 1 开始的迭代器。You define such a function (doc here):
and call it from your modules so:
The function raiseErr will print info about the place you called it.
More elaborate, you can do so:
Other possibility is to define this function:
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)
.除了 AndiDog 关于
inspect
的回答之外,请注意pdb
允许您在堆栈中上下导航,检查局部变量等。标准库pdb.py
中的源代码可以帮助您学习如何执行此类操作。In addition to AndiDog's answer about
inspect
, note thatpdb
lets you navigate up and down the stack, inspecting locals and such things. The source in the standard librarypdb.py
could be helpful to you in learning how to do such things.