[英]ModuleNotFoundError: No module named <module> on importlib import_module
I am trying to create a module hooker, that corrects module name while importing a module, here is the small prototype:我正在尝试创建一个模块挂钩,在导入模块时更正模块名称,这是小原型:
from sys import meta_path, modules
from importlib import import_module
class Hook:
spellcheck = {"maht": "math", "randon": "random", "ramdom": "random"}
def find_module(self, module, _):
if module in self.spellcheck:
return self
def load_module(self, module):
modules[module] = import_module(self.spellcheck[module])
return modules[module]
meta_path.clear()
meta_path.append(Hook())
import randon
import maht
The error:错误:
Traceback (most recent call last):
File "/home/yagiz/Desktop/spellchecker.py", line 20, in <module>
import randon
File "/home/yagiz/Desktop/spellchecker.py", line 13, in load_module
modules[module] = import_module(self.spellcheck[module])
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'random'
Current machine, ubuntu 18.04 and python 3.6.9 also i tried with newer versions of python当前机器,ubuntu 18.04 和 python 3.6.9 我也尝试使用较新版本的 python
It is all about meta_path.clear()
, just remove it.这都是关于
meta_path.clear()
的,只需将其删除即可。
By using the clear
function, you are clearing meta_path
from the builtin modules, so even the builtin module random
couldn't be loaded.通过使用
clear
function,您正在从内置模块中清除meta_path
,因此即使是内置模块random
也无法加载。
Edit:编辑:
As discussed through comments, you can provide a misspelling error message instead of accepting loading the misspelled module.正如通过评论所讨论的,您可以提供拼写错误的错误消息,而不是接受加载拼写错误的模块。 This can be done by updating your
Hook
class to:这可以通过将您的
Hook
class 更新为:
class Hook:
spellcheck = {"maht": "math", "randon": "random", "ramdom": "random"}
def find_module(self, module, _):
if module in self.spellcheck:
return self
def load_module(self, module):
raise ImportError(f"No module named '{module}'. Did you mean '{self.spellcheck[module]}'?")
Now, if you import one of the misspelled modules:现在,如果您导入其中一个拼写错误的模块:
import randon
Output: Output:
ImportError: No module named 'randon'. Did you mean 'random'?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.