在 Python 中的另一个函数中获取调用者函数名?

如果你有两个功能,比如:

def A
def B

A 呼叫 B,你能知道是谁在 B 内部呼叫 B 吗,比如:

def A () :
B ()


def B () :
this.caller.name
122251 次浏览

您可以使用 视察模块获得所需的信息。它的 方法返回帧记录列表。

  • 对于 巨蟒2,每个帧记录是一个列表。每条记录中的第三个元素是调用者名称。你想要的是这个:

    >>> 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]
    

    print(inspect.stack()[1].function)
    

    在上面的代码。

注(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 方法。

您可以使用日志记录模块并在 BaseConfig ()中指定% (funName) 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')

有两种方法,使用 sysinspect模块:

  • 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)

这对我有用! : D

>>> def a():
...     import sys
...     print sys._getframe(1).f_code.co_name
...
>>> def b():
...     a()
...
...
>>> b()
b
>>>