简体   繁体   English

如何以编程方式检查Python中异常的堆栈跟踪?

[英]How can you programmatically inspect the stack trace of an exception in Python?

When an exception occurs in Python, can you inspect the stack? 当Python中发生异常时,您可以检查堆栈吗? Can you determine its depth? 你能确定它的深度吗? I've looked at the traceback module, but I can't figure out how to use it. 我查看了traceback模块,但我无法弄清楚如何使用它。

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. 我的目标是捕获在解析eval表达式期间发生的任何异常,而不会捕获它可能调用的任何函数抛出的异常。 Don't berate me for using eval. 不要因为使用eval而责备我。 It wasn't my decision. 这不是我的决定。

NOTE: I want to do this programmatically, not interactively. 注意:我想以编程方式而不是交互方式执行此操作。

traceback is enough - and I suppose that documentation describes it rather well. traceback就足够了 - 我认为文档描述得相当好。 Simplified example: 简化示例:

import sys
import traceback

try:
    eval('a')
except NameError:
    traceback.print_exc(file=sys.stdout)

You can use the inspect module which has some utility functions for tracing. 您可以使用具有一些实用功能的inspect模块进行跟踪。 Have a look at the overview of properties of the frame objects. 查看框架对象属性概述

I like the traceback module. 我喜欢回溯模块。

You can get a traceback object using sys.exc_info() . 您可以使用sys.exc_info()获取回溯对象。 Then you can use that object to get a list preprocessed list of traceback entries using traceback.extract_tb() . 然后,您可以使用该对象使用traceback.extract_tb()获取列表预处理的回溯条目列表。 Then you can get a readable list using traceback.format_list() as follows: 然后,您可以使用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 和追溯模块: http//docs.python.org/library/traceback.html

You define such a function ( doc here ): 你定义了这样一个函数( doc here ):

def raiseErr():
   for f in inspect.stack(): print '-', inspect.getframeinfo(f[0])

and call it from your modules so: 并从您的模块中调用它,以便:

raiseErr()

The function raiseErr will 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)从1开始创建一个迭代器。

In addition to AndiDog's answer about inspect , note that pdb lets you navigate up and down the stack, inspecting locals and such things. 除了AndiDog关于inspect的答案之外,请注意pdb允许您在堆栈中上下导航,检查本地人等。 The source in the standard library pdb.py could be helpful to you in learning how to do such things. 标准库pdb.py的源代码可以帮助您学习如何执行此类操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM