在Python v3.7.x中,被调用函数如何获取调用函数的名称?

问题描述 投票:1回答:1

Pythonistas,

在Python v3.7.x或更高版本中,被调用函数如何获取调用函数的名称...没有将调用函数的名称编程为参数?

在下面的代码示例中,NAME_OF_CALLING_FUNCTION如何填充... well ...调用函数的名称? (说...与标准库有关?Dunders / Magic Names?)

  • 需要明确的是:此协助请求不是关于使用Python的日志记录模块(此处仅用作示例);它是关于一个被调用的函数,能够自动神奇地获取调用函数的名称。

示例代码:

logging.basicConfig(filename='my_log_file.log',
    level = logging.DEBUG,
    format = A_VALID_FORMAT_STRING)

def logging_function(log_message):
    #Simplified for StackOverflow
    msg = str(NAME_OF_CALLING_FUNCTION) + ' DEBUG: Something...'
    logging.debug(msg)

def caller_one():
    #Simplified for StackOverflow
    logging_function(DIAGNOSTIC_MESSAGE_ONE)
    return(0)

def caller_two():
    #Simplified for StackOverflow
    logging_function(DIAGNOSTIC_MESSAGE_TWO)
    return(0)

def main():
    #Simplified for StackOverflow
    caller_one()
    caller_two()

理想情况下,当caller_one()caller_two()执行时,my_log_file.log将包含以下内容:

DATE/TIME Calling function: caller_one DEBUG: Something...
DATE/TIME Calling function: caller_two DEBUG: Something...

非常感谢您提供的任何帮助!

感激之情,Plane Wryter

python python-3.x
1个回答
2
投票

使用inspect模块。来自this source

import inspect
# functions
def whoami():
    return inspect.stack()[1][3]
def whosdaddy():
    return inspect.stack()[2][3]
def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()
def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
johny = bar
# call them!
foo()
bar()
johny()
hello, I'm foo, daddy is ?
hello, I'm bar, daddy is foo
hello, I'm bar, daddy is ?
hello, I'm bar, daddy is ?

在你的情况下:

msg = str(inspect.stack()[1].function) + ' DEBUG: Something...'

例:

import inspect

def logging_function(log_message):
    #Simplified for StackOverflow
    msg = str(inspect.stack()[1].function) + ' DEBUG: Something...'
    print(msg)

def f1():
    logging_function("")

def f2():
    logging_function("")

f1()
f2()
f1 DEBUG: Something...
f2 DEBUG: Something...
© www.soinside.com 2019 - 2024. All rights reserved.