Pythonistas
在Python v3.7.x或更高版本中,被调用函数如何获得调用函数的名称...而无需将调用函数的名称编程为自变量?
在下面的代码示例中,如何用...好吧...调用函数的名称填充 NAME_OF_CALLING_FUNCTION ? (说...与标准库有关吗?Dunders /魔术名称?)
示例代码:
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
答案 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...