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

Joh*_*aff 12 python inspect

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

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

import inspect

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

def foo():
    print(whoami())
Run Code Online (Sandbox Code Playgroud)

目前它打印foo,我想打印 whoami

小智 23

你可能想要inspect.getframeinfo(frame).function:

import inspect

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

def foo():
    print(whoami())

foo()
Run Code Online (Sandbox Code Playgroud)

版画

whoami
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用:“返回inspect.getouterframes(inspect.currentframe())[1].function” (4认同)

Eri*_*ric 13

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

你考虑过装饰师吗?

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")
Run Code Online (Sandbox Code Playgroud)


小智 12

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

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

您可以调整格式化程序以记录函数名称:

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()
Run Code Online (Sandbox Code Playgroud)

版画

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
Run Code Online (Sandbox Code Playgroud)

  • @JohnKaff:我认为你在这里有一个X/Y问题的案例,应该问一个关于如何在python中最好地记录函数调用(带参数,类方法等)的新问题 (2认同)

Fil*_*ppy 7

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

import inspect

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

# Example:
def whoami():
    print(current_method_name())

whoami()
Run Code Online (Sandbox Code Playgroud)

-> 输出是 whoami


Jam*_*979 5

调用sys._getframe()以获取frame类实例。该f_code.co_name成员保存函数名称。

sys._getframe(0).f_code.co_name
Run Code Online (Sandbox Code Playgroud)

添加一个简单的辅助函数func_name()来包装调用

import sys

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

def func1():
    print(func_name())

func1()  # prints 'func1'
Run Code Online (Sandbox Code Playgroud)