动态获取模块

Raj*_*etu 3 python module python-2.7

我有一些像这样的模块:

    Drivers/
        a.py
        b.py
        c.py
Run Code Online (Sandbox Code Playgroud)

现在我想根据变量值来调用它们.让我们考虑驱动程序是我将获取变量名称的变量.

    if driver=='a':
        #then call the driver a and execute.
        a.somefunction()
    if driver=='b':
        #then call the driver b and execute
Run Code Online (Sandbox Code Playgroud)

我知道if语句中的驱动程序的值是字符串类型值,而在if语句中我们必须调用模块.有没有办法转换它.??

Dan*_*iel 5

如果您在python的搜索路径中的"Drivers /"目录,只需导入模块并调用该函数:

import importlib
module = importlib.import_module(driver)
module.some_function()
Run Code Online (Sandbox Code Playgroud)