【问题标题】:Python: Get running methods name from external method [duplicate]Python:从外部方法获取正在运行的方法名称[重复]
【发布时间】:2021-11-16 12:23:44
【问题描述】:

我正在创建一个自定义日志函数,它需要获取运行它的方法的名称。如何将方法的名称传递给日志函数。例如,这个:

def log(msg):
    print(f'{runningMethod}: {msg}') # runningMethod is the intended parameter to get passed
    return


def testFunc():
    log("Running")
    return

testFunc()

应该输出这个:

testFunc:正在运行

要求 log() 只接受一个参数

【问题讨论】:

    标签: python logging


    【解决方案1】:

    使用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()
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 2023-03-10
      • 2016-10-12
      • 1970-01-01
      • 2015-05-22
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多