【发布时间】:2015-07-21 09:04:59
【问题描述】:
我如何加载一个未内置的 python 模块。我正在尝试为我正在处理的一个小项目创建一个插件系统。如何将这些“插件”加载到 python 中?并且,不调用“导入模块”,而是使用字符串来引用模块。
【问题讨论】:
我如何加载一个未内置的 python 模块。我正在尝试为我正在处理的一个小项目创建一个插件系统。如何将这些“插件”加载到 python 中?并且,不调用“导入模块”,而是使用字符串来引用模块。
【问题讨论】:
假设/path/to/my/custom/module.py 有一个模块包含以下内容:
# /path/to/my/custom/module.py
test_var = 'hello'
def test_func():
print(test_var)
我们可以使用以下代码导入这个模块:
import importlib.machinery
myfile = '/path/to/my/custom/module.py'
sfl = importlib.machinery.SourceFileLoader('mymod', myfile)
mymod = sfl.load_module()
模块被导入并分配给变量mymod。然后我们可以访问模块的内容:
mymod.test_var
# prints 'hello' to the console
mymod.test_func()
# also prints 'hello' to the console
使用importlib.import_module
例如,如果您想从应用程序根文件夹中的 settings.py 文件导入设置,您可以使用
_settings = importlib.import_module('settings')
流行的任务队列包Celery大量使用这个,这里就不给你代码示例了,请查看他们的git repository
【讨论】: