【问题标题】:Convert string into a function call将字符串转换为函数调用
【发布时间】:2014-03-28 01:54:57
【问题描述】:

我有一个带有函数确切名称的字符串变量,例如

ran_test_opt = "random_aoi"

函数如下所示:

def random_aoi():
  logging.info("Random AOI Test").

字符串是从配置文件中接收的,因此无法更改。有没有办法可以将字符串转换为实际的函数调用,以便

ran_test_opt()

会运行random_aoi 函数吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    当然,你可以使用globals:

    func_to_run = globals()[ran_test_opt]
    func_to_run()
    

    或者,如果它在不同的模块中,你可以使用getattr

    func_to_run = getattr(other_module, ran_test_opt)
    func_to_run()
    

    【讨论】:

      【解决方案2】:

      还有另一种方法可以从它的字符串表示中调用函数,只需使用 eval("func()") 它会执行它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-27
        • 2018-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多