在 Python 2.7 中获取调用者的函数对象?
Get function object of caller in Python 2.7?
在玩 inspect
和阅读其他问题时,我仍然无法弄清楚如何比加载模块的路径,然后在其中找到函数。
换句话说,您将如何完成以下操作以便 caller()
returns 一个方法对象?
import inspect
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3] # function NAME string
# TODO: now what?
return func
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
记住,我已经知道函数名称,但我要访问的是调用代码在 运行 中的函数对象。所需的结果是:
peter cried 'WOLF!'
完成!感谢用户61612,我已经完成了这段代码:
import imp, inspect, sys
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3]
return code.f_globals[name]
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
太棒了!
框架对象具有 f_globals
attribute:
import inspect
def caller():
tup = inspect.stack()[2]
return tup[0].f_globals[tup[3]] # <function peter at address>
def cry_wolf():
func = caller()
print("%s cried 'WOLF!'" % (func.__name__,)) # peter cried 'WOLF!'
def peter():
cry_wolf()
在玩 inspect
和阅读其他问题时,我仍然无法弄清楚如何比加载模块的路径,然后在其中找到函数。
换句话说,您将如何完成以下操作以便 caller()
returns 一个方法对象?
import inspect
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3] # function NAME string
# TODO: now what?
return func
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
记住,我已经知道函数名称,但我要访问的是调用代码在 运行 中的函数对象。所需的结果是:
peter cried 'WOLF!'
完成!感谢用户61612,我已经完成了这段代码:
import imp, inspect, sys
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3]
return code.f_globals[name]
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
太棒了!
框架对象具有 f_globals
attribute:
import inspect
def caller():
tup = inspect.stack()[2]
return tup[0].f_globals[tup[3]] # <function peter at address>
def cry_wolf():
func = caller()
print("%s cried 'WOLF!'" % (func.__name__,)) # peter cried 'WOLF!'
def peter():
cry_wolf()