iTa*_*ayb 8 python callstack introspection
我想获得有关python中特定函数的调用者的信息.例如:
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."
Run Code Online (Sandbox Code Playgroud)
有可能与python?
Mar*_*ers 11
是的,该sys._getframe()
函数允许您从当前执行堆栈中检索帧,然后可以使用inspect
模块中的方法和文档进行检查; 您将在f_locals
属性中查找特定的本地人以及f_code
信息:
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__)
Run Code Online (Sandbox Code Playgroud)
请注意,您需要注意检测每个帧中找到的信息类型.