我正在尝试创建一个模块钩子,它在导入模块时更正模块名称,下面是一个小原型:
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
错误:
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'
当前的机器,Ubuntu18.04和Python3.6.9,我也尝试了更新版本的python
这一切都是关于
meta_path.clear()
,只需删除它通过使用
clear
函数,可以从内置模块中清除meta_path
,因此即使是内置模块random
也无法加载编辑:
如注释所述,您可以提供拼写错误的错误消息,而不是接受加载拼写错误的模块。这可以通过将
Hook
类更新为:现在,如果导入拼写错误的模块之一:
输出:
相关问题 更多 >
编程相关推荐