ModuleNotFoundError:在importlib import\u模块上没有名为<module>的模块

2024-09-27 19:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个模块钩子,它在导入模块时更正模块名称,下面是一个小原型:

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


Tags: 模块pathinpyimportselfmodulesreturn
1条回答
网友
1楼 · 发布于 2024-09-27 19:20:37

这一切都是关于meta_path.clear(),只需删除它

通过使用clear函数,可以从内置模块中清除meta_path,因此即使是内置模块random也无法加载

编辑:

如注释所述,您可以提供拼写错误的错误消息,而不是接受加载拼写错误的模块。这可以通过将Hook类更新为:

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]}'?")

现在,如果导入拼写错误的模块之一:

import randon

输出:

ImportError: No module named 'randon'. Did you mean 'random'?

相关问题 更多 >

    热门问题