1

在下面的示例代码中,我打算获取装饰函数的被调用者的堆栈帧。假设,装饰函数,power(下面),调用 pwr 函数并且有一个例外,我想获取 pwr 的堆栈帧(打印函数参数)。对于在 api 中公开的函数,它的参数和响应被打印,但是模块内部的函数和 api 调用的函数,我想得到那些堆栈帧。

import inspect
def api(func):
    def decor(*args, **kwargs):
        try:
            print "Request %s %s %s" % ( func.__name__, args, kwargs)
            response = func(*args,**kwargs)
            print "response %s", response
            return response
        except Exception, e:
            print "exception in %s", func.__name__
            for frame in inspect.stack():
                print frame[3]
            raise e
    return decor

@api
def power(a,b):
    return pwr(a,b)

def pwr():
   ...
   ...

当我运行代码时,在异常期间,我从 decor 和 up 获取堆栈帧,但不是 func 或更低。任何人都可以建议吗?

4

2 回答 2

2

If you want to look at the context in which the exception occurred, you need to look at the third value (the "traceback object") returned from sys.exc_info(). The traceback module has some useful functions for handling these objects: you might be able to make use of traceback.print_tb.

For example:

>>> import sys, traceback
>>> try: raise Exception()
... except: traceback.print_tb(sys.exc_info()[2])
... 
  File "<stdin>", line 1, in <module>
于 2013-04-04T11:34:48.443 回答
0

在函数返回或引发异常之后,您无法访问框架,因为框架根本不再存在。如果您确实想出于某些调试/分析目的访问函数框架并且无法修改该函数,请考虑使用sys.setprofileor sys.settrace。回调将作为参数传递给框架。

于 2013-04-04T10:35:36.163 回答