Python 执行由名称标识的函数

Python 执行由名称标识的函数,python,Python,我想运行一个由字符串标识的函数 toRun = 'testFunction' def testFunction(): log.info('In the function'); run(toRun) 其中run将是我需要使用的任何命令。我试过使用exec/eval,运气不好。你可以使用eval eval("testFunction()") # must have brackets in order to call the function 或者你可以 toRun += "()"

我想运行一个由字符串标识的函数

toRun = 'testFunction'

def testFunction():
    log.info('In the function');

run(toRun)

其中
run
将是我需要使用的任何命令。我试过使用
exec
/
eval
,运气不好。

你可以使用
eval

eval("testFunction()") # must have brackets in order to call the function
或者你可以

toRun += "()"

eval("eval(toRun)")

您可以使用
eval

eval("testFunction()") # must have brackets in order to call the function
或者你可以

toRun += "()"

eval("eval(toRun)")
返回包含当前作用域中引用的dict

locals()[toRun]()
返回包含当前作用域中引用的dict

locals()[toRun]()

最好使用将字符串映射到函数的字典

def func1():
    print("in function 1")

def func2():
    print("in function 2")


functions = {
    "func1": func1,
    "func2": func2
}

# Get function by name.
the_func = functions["func1"]
# Execute it.
the_func()

最好使用将字符串映射到函数的字典

def func1():
    print("in function 1")

def func2():
    print("in function 2")


functions = {
    "func1": func1,
    "func2": func2
}

# Get function by name.
the_func = functions["func1"]
# Execute it.
the_func()
内置函数可用于返回作为参数传递的对象的命名属性

示例

>>> import sys
>>> def function():
...     print 'hello'
... 
>>> fun_object = getattr( sys.modules[ __name__ ], 'function')
>>> fun_object()
hello
它的作用

  • sys.modules[\u\u name\u\u]
    返回当前模块对象

  • getattr(sys.modules[\uu name\uu],“function”)
    通过对象的名称
    function
    返回一个属性,该对象是当前对象

  • fun\u object()
    调用返回的函数
内置函数可用于返回作为参数传递的对象的命名属性

示例

>>> import sys
>>> def function():
...     print 'hello'
... 
>>> fun_object = getattr( sys.modules[ __name__ ], 'function')
>>> fun_object()
hello
它的作用

  • sys.modules[\u\u name\u\u]
    返回当前模块对象

  • getattr(sys.modules[\uu name\uu],“function”)
    通过对象的名称
    function
    返回一个属性,该对象是当前对象

  • fun\u object()
    调用返回的函数
的可能副本的可能副本您可以使用
eval
。但是如果不是绝对必要的话就不要这样做。你可以使用
eval
。但如果这不是绝对必要的,就不要这样做。