如何在python中获取该函数内的当前函数名称

时间:2015-10-16 03:55:47

标签: python inspect

为了我的记录目的,我想记录我的代码所在的所有函数名称

谁调用函数无关紧要,我想要声明此行的函数名称

import inspect

def whoami():
    return inspect.stack()[1][3]

def foo():
    print(whoami())

目前打印foo,我想打印whoami

5 个答案:

答案 0 :(得分:21)

您可能需要inspect.getframeinfo(frame).function

import inspect

def whoami(): 
    frame = inspect.currentframe()
    return inspect.getframeinfo(frame).function

def foo():
    print(whoami())

foo()

打印

whoami

答案 1 :(得分:12)

  

为了我的记录目的,我想记录我的代码所在的所有函数名称

你考虑过装饰师吗?

import functools
def logme(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        print(f.__name__)
        return f(*args, **kwargs)
    return wrapped


@logme
def myfunction();
    print("Doing some stuff")

答案 2 :(得分:11)

实际上,Eric的答案指出了如果这是关于记录的方式:

  

为了我的记录目的,我想记录我的代码所在的所有函数名称

您可以调整格式化程序以记录function name

import logging               

def whoami():
    logging.info("Now I'm there")

def foo():
    logging.info("I'm here")
    whoami()
    logging.info("I'm back here again")

logging.basicConfig(
    format="%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s",
    level=logging.INFO)
foo()

打印

2015-10-16 16:29:34,227 [INFO] foo: I'm here
2015-10-16 16:29:34,227 [INFO] whoami: Now I'm there
2015-10-16 16:29:34,227 [INFO] foo: I'm back here again

答案 3 :(得分:2)

使用f_code.co_name返回的堆栈帧的sys._getframe()成员。

sys._getframe(0).f_code.co_name

例如,在whoami()函数中,

import sys

def whoami(): 
    return sys._getframe(1).f_code.co_name

def func1():
    print(whoami())

func1()  # prints 'func1'

答案 4 :(得分:2)

这个简单的可重用方法返回调用者/父函数的名称:

def current_method_name():
    # [0] is this method's frame, [1] is the parent's frame - which we want
    return inspect.stack()[1].function  

示例:

def whoami():
    print(current_method_name())

whoami()

-> 输出为 whoami

相关问题