在Python 3中加载Python模块
在Python 3中加载Python模块
如何加载一个不是内置的Python模块。我正在尝试为我正在处理的小项目创建一个插件系统。如何将这些“插件”加载到Python中?并且,使用字符串来引用模块而不是调用“import module”。
admin 更改状态以发布 2023年5月25日
看一下importlib
选项1: 导入任意路径下的任意文件
假设有一个模块位于/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
选项2: 从包中导入模块
使用importlib.import_module
例如,如果您想从应用程序根文件夹中的settings.py文件导入设置,可以使用
_settings = importlib.import_module('settings')
流行的任务队列包Celery
经常使用这个方法。不在这里提供代码示例,请查看他们的Git存储库