【问题标题】:Loading python modules in Python 3在 Python 3 中加载 python 模块
【发布时间】:2015-07-21 09:04:59
【问题描述】:

我如何加载一个未内置的 python 模块。我正在尝试为我正在处理的一个小项目创建一个插件系统。如何将这些“插件”加载到 python 中?并且,不调用“导入模块”,而是使用字符串来引用模块。

【问题讨论】:

标签: python-3.x python-module


【解决方案1】:

看看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 repository

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2019-10-07
    相关资源
    最近更新 更多