Python: 从外部方法获取 运行 方法名
Python: Get running methods name from external method
我正在创建一个自定义日志函数,它需要获取方法的名称 运行。如何获取传递给日志函数的方法名称。例如,这个:
def log(msg):
print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
return
def testFunc():
log("Running")
return
testFunc()
应该输出这个:
testFunc: Running
要求 log() 只接受一个参数
使用inspect.currentframe()
并取上一个:
例如:
import inspect
def log(msg):
caller = inspect.currentframe().f_back
runningMethod = caller.f_code.co_name
print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
return
def testFunc():
log("Running")
return
testFunc()
我正在创建一个自定义日志函数,它需要获取方法的名称 运行。如何获取传递给日志函数的方法名称。例如,这个:
def log(msg):
print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
return
def testFunc():
log("Running")
return
testFunc()
应该输出这个:
testFunc: Running
要求 log() 只接受一个参数
使用inspect.currentframe()
并取上一个:
例如:
import inspect
def log(msg):
caller = inspect.currentframe().f_back
runningMethod = caller.f_code.co_name
print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
return
def testFunc():
log("Running")
return
testFunc()