ModuleNotFoundError: 没有名为“__main__.xxxx"的模块;'__main__' 不是一个包 [英] ModuleNotFoundError: No module named '__main__.xxxx'; '__main__' is not a package

查看:42
本文介绍了ModuleNotFoundError: 没有名为“__main__.xxxx"的模块;'__main__' 不是一个包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在尝试在 Python3 中工作并使用绝对导入将一个模块导入另一个模块,但出现错误 ModuleNotFoundError: No module named '__main__.moduleB';'__main__' 不是包.考虑这个项目结构:

Currently trying to work in Python3 and use absolute imports to import one module into another but I get the error ModuleNotFoundError: No module named '__main__.moduleB'; '__main__' is not a package. Consider this project structure:

proj
    __init__.py3 (empty)
    moduleA.py3
    moduleB.py3

moduleA.py3

moduleA.py3

from .moduleB import ModuleB
ModuleB.hello()

moduleB.py3

moduleB.py3

class ModuleB:
    def hello():
        print("hello world")

然后运行 ​​python3 moduleA.py3 给出错误.这里需要改变什么?

Then running python3 moduleA.py3 gives the error. What needs to be changed here?

推荐答案

.moduleB 是相对导入.相对仅在先导入或加载父模块时才有效.这意味着您需要在当前运行时环境中的某处导入 proj.当您使用命令 python3 moduleA.py3 时,没有机会导入父模块.您可以:

.moduleB is a relative import. Relative only works when the parent module is imported or loaded first. That means you need to have proj imported somewhere in your current runtime environment. When you are are using command python3 moduleA.py3, it is getting no chance to import parent module. You can:

  • from proj.moduleB import moduleB OR
  • 您可以创建另一个脚本,例如 run.py,以调用 from proj import moduleA
  • from proj.moduleB import moduleB OR
  • You can create another script, let's say run.py, to invoke from proj import moduleA

祝您前往 Python 神奇之地的旅程好运.

Good luck with your journey to the awesome land of Python.

这篇关于ModuleNotFoundError: 没有名为“__main__.xxxx"的模块;'__main__' 不是一个包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆