使用 python 获取该函数内的当前函数名称

问题描述 投票:0回答:6

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

不管是谁在调用函数,我想要我声明这一行的函数名称

import inspect

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

def foo():
    print(whoami())

目前打印

foo
,我想打印
whoami

python inspect
6个回答
53
投票

你可能想要

inspect.getframeinfo(frame).function

import inspect

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

def foo():
    print(whoami())

foo()

版画

whoami

29
投票

实际上,如果这是关于 logging

,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()

打印

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

19
投票

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

你考虑过装饰器吗?

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

10
投票

调用

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

sys._getframe(0).f_code.co_name

添加一个简单的辅助函数

func_name()
来包装调用

import sys

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

def func1():
    print(func_name())

func1()  # prints 'func1'

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

->输出是

whoami


1
投票

在此处添加答案,因为包含类名和函数可能很有用。

这会检查

self
cls
约定,包括类名。

def name_of_caller(frame=1):
    """
    Return "class.function_name" of the caller or just "function_name".
    """
    frame = sys._getframe(frame)
    fn_name = frame.f_code.co_name
    var_names = frame.f_code.co_varnames
    if var_names:
        if var_names[0] == "self":
            self_obj = frame.f_locals.get("self")
            if self_obj is not None:
                return type(self_obj).__name__ + "." + fn_name
        if var_names[0] == "cls":
            cls_obj = frame.f_locals.get("cls")
            if cls_obj is not None:
                return cls_obj.__name__ + "." + fn_name
    return fn_name

© www.soinside.com 2019 - 2024. All rights reserved.