在python中获取函数调用者的信息

在python中获取函数调用者的信息

问题描述:

我想获取有关python中特定函数的调用者的信息。例如:

I want to get information about the callers of a specific function in python. For example:

class SomeClass():
    def __init__(self, x):
        self.x = x
    def caller(self):
        return special_func(self.x)

def special_func(x):
    print "My caller is the 'caller' function in an 'SomeClass' class."

是否可以使用python?

Is it possible with python?

是的, sys._getframe() 函数让您从当前执行堆栈中检索框架,然后可以使用 检查模块;您将在 f_locals 属性中查找特定的本地人,以及 f_code 信息:

Yes, the sys._getframe() function let's you retrieve frames from the current execution stack, which you can then inspect with the methods and documentation found in the inspect module; you'll be looking for specific locals in the f_locals attribute, as well as for the f_code information:

import sys
def special_func(x):
    callingframe = sys._getframe(1)
    print 'My caller is the %r function in a %r class' % (
        callingframe.f_code.co_name, 
        callingframe.f_locals['self'].__class__.__name__)

请注意,您需要格外小心以检测在每个帧中发现的信息。

Note that you'll need to take some care to detect what kind of information you find in each frame.

sys._getframe()返回一个框架对象,您可以按照 f_back 参考。或者,您可以使用 inspect.stack() 函数生成带有附加信息的框架列表。

sys._getframe() returns a frame object, you can chain through the whole stack by following the f_back reference on each. Or you can use the inspect.stack() function to produce a lists of frames with additional information.