python - 动态获取模块

标签 python python-2.7 module

我有一些像这样的模块:

    Drivers/
        a.py
        b.py
        c.py

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

    if driver=='a':
        #then call the driver a and execute.
        a.somefunction()
    if driver=='b':
        #then call the driver b and execute

我知道我们在 if 语句中从驱动程序中获取的值是一个字符串类型的值,并且在 if 语句中我们必须调用一个模块。 有什么办法可以转换吗??

最佳答案

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

import importlib
module = importlib.import_module(driver)
module.some_function()

关于python - 动态获取模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720403/

相关文章:

python - 如何在pygame中获取屏幕外的像素颜色?

python - tweepy流到sqlite数据库-语法错误

python - BeautifulSoup stripped_strings 中有太多换行符...如何使纯文本格式更接近原始 html?

python - 我可以在本地类中使用导入模块中的函数吗? (Python)

import - 第三方库上的 Rust `unresolved import`

haskell - SML模块系统和Haskell的Type和Typeclass系统在功能上有什么区别?

python - 如何在Python中实现b进制扩展?

python - Hello World,继续运行 appengine : ctypes error

python - 我如何将音量添加到 pyalsaaudio 中的 current_volume 列表?

google-app-engine - Appengine NDB : Putting 880 rows, 超出数据存储区写入操作配额。为什么?