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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33162319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:54:36  来源:igfitidea点击:

How can get current function name inside that function in python

pythoninspect

提问by John Kaff

For my logging purpose i want to log all the names of functions where my code is going

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

Does not matter who is calling the function , i want the the function name in which i declare this line

谁在调用函数并不重要,我想要我声明这一行的函数名

import inspect

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

def foo():
    print(whoami())

currently it prints foo, i want to print whoami

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

采纳答案by John Kaff

You probably want inspect.getframeinfo(frame).function:

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

import inspect

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

def foo():
    print(whoami())

foo()

prints

印刷

whoami

回答by Eric

For my logging purpose i want to log all the names of functions where my code is going

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

Have you considered decorators?

你考虑过装饰器吗?

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

回答by Eric

Actually, Eric's answer points the way if this is about logging:

实际上,如果这是关于日志记录,Eric 的回答指明了方向:

For my logging purpose i want to log all the names of functions where my code is going

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

You can adjust the formatter to log the 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()

prints

印刷

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

回答by JamesThomasMoon1979

Use f_code.co_namemember of the stack frame returned by sys._getframe().

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

sys._getframe(0).f_code.co_name

For example, in a whoami()function,

例如,在一个whoami()函数中,

import sys

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

def func1():
    print(whoami())

func1()  # prints 'func1'