首页 > 解决方案 > 在 python 3.6 中加载模块

问题描述

当我将模块加载到Python 3.6.

   spec = importlib.util.spec_from_file_location(load_module,path)
   mod = importlib.util.module_from_spec(spec)
   spec.loader.exec_module(mod)

我收到以下错误:

mod = importlib.util.module_from_spec(spec) File "<frozen importlib._bootstrap>",
line 568, in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader'

我该如何以正确的方式做到这一点?

过去,我一直在使用:

mod = importlib.import_module(load_module)

与路径中的模块路径。这适用于python 3.7

标签: pythonpython-3.x

解决方案


因此您可以像这样以编程方式导入模块:

my_module = importlib.import_module('my_module')

要指定自定义路径,您可以使用:

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

如果您收到以下错误,则表示spec_from_file_location找不到您指定并返回的模块和路径None

in module_from_spec AttributeError: 'NoneType' object has no attribute 'loader'

推荐阅读