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

时间:2019-04-05 02:08:01

标签: python python-3.x

Pythonistas

在Python v3.7.x或更高版本中,被调用函数如何获得调用函数的名称...而无需将调用函数的名称编程为自变量?

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

  • 要明确:此帮助请求不是关于使用 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...

在此先感谢您提供的任何帮助!

感谢, 飞机Wryter

1 个答案:

答案 0 :(得分: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...