python - 在 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
解决方案
因此您可以像这样以编程方式导入模块:
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'
推荐阅读
- oracle - 从脚本创建 Oracle DDL 对象时出错:“无效的普通用户或角色名称”、“文件已经是数据库的一部分”等
- spring - 如何在 r2dbc-postgresql 中使用 EnumCodec
- reactjs - React Native 删除 Flatlist 中的底部空间
- python - Scipy 差分进化初始解输入
- electron - 最小化后电子高度变化,恢复
- python - 或者当使用 Python 存在 NaN 值时逻辑不起作用
- youtube-api - 为什么 YouTube Data API 搜索经常会找到 0 个结果,而普通的 YouTube 网站搜索会产生很多结果?
- android - 错误:在 FirebaseMessagingService 上注入时无法访问 RemoteMessage
- oracle-sqldeveloper - 根据表 1 中字符串内容的条件连接两个表
- python - 如何使用 Pythons Multiprocessing 库的 Process 类多次运行一个函数?