gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:04:13 25 4
gpt4 key购买 nike

Python 爱好者,

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

在下面的代码示例中,如何用……嗯……调用函数的名称填充NAME_OF_CALLING_FUNCTION? (比如说……与标准库有关?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...

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

怀着感恩的心,飞机书写器

最佳答案

使用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...

关于python - Python v3.7.x中,被调用函数如何获取调用函数的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com