如果你有两个函数:
def A
def B
如果 A 调用了 B,你能否在 B 内部获取调用 B 的是谁,例如:
def A () :
B ()
def B () :
this.caller.name
如果你有两个函数:
def A
def B
如果 A 调用了 B,你能否在 B 内部获取调用 B 的是谁,例如:
def A () :
B ()
def B () :
this.caller.name
您可以使用inspect模块获取所需信息。它的stack方法返回帧记录列表。
For Python 2 each frame record is a list. The third element in each record is the caller name. What you want is this:
>>> import inspect
>>> def f():
... print inspect.stack()[1][3]
...
>>> def g():
... f()
...
>>> g()
g
For Python 3.5+, each frame record is a named tuple so you need to replace
print inspect.stack()[1][3]
with
print(inspect.stack()[1].function)
on the above code.
inspect.currentframe().f_back.f_code.co_name
,这与Python版本或实现无关。 - 1313einspect.currentframe()
也取决于Python的实现,因为如果你阅读inspect.py
的源代码,它们都使用sys._getframe()
。 - Marco Sullaprint(inspect.stack()[1].function, inspect.stack()[1].filename)
- 10mjg__init__
内部,是否有获取相同信息的替代方法? - t3chb0t有两种方法,使用sys
和inspect
模块:
sys._getframe(1).f_code.co_name
inspect.stack()[1][3]
stack()
形式不太易读,而且依赖于实现,因为它调用了sys._getframe()
,参见从inspect.py
中提取的内容:
def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context)
timeit
)?我认为它更快,因为它似乎不会产生函数调用和两个列表查找。但是在Python中可能会隐藏一些东西,所以最好的方法是使用timeit
进行测试。请告诉我们你的发现。 - Eric注意(2018年6月):今天,我可能会使用inspect
模块,请参见其他回答
可以像下面的示例中使用sys._getframe(1).f_code.co_name
:
>>> def foo():
... global x
... x = sys._getframe(1)
...
>>> def y(): foo()
...
>>> y()
>>> x.f_code.co_name
'y'
>>>
重要提示:从_getframe
方法名称中可以明显看出(嘿,它以下划线开头),它不是一个人们应该盲目依赖的 API 方法。
>>> def a():
... import sys
... print sys._getframe(1).f_code.co_name
...
>>> def b():
... a()
...
...
>>> b()
b
>>>
inspect.stack()
快多了,至少快了1000倍。 - Conchylicultor您可以使用logging模块并在BaseConfig()中指定%(funcName)s选项。
该选项与函数名称相关联。import logging
logging.basicConfig(
filename='/tmp/test.log',
level=logging.DEBUG,
format='%(asctime)s | %(levelname)s | %(funcName)s |%(message)s',
)
def A():
logging.info('info')