ModuleNotFoundError:没有名为'__main __。xxxx'的模块; '__main__'不是包 [英] ModuleNotFoundError: No module named '__main__.xxxx'; '__main__' is not a package

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

问题描述

目前正在尝试使用Python3并使用绝对导入将一个模块导入另一个模块但我收到错误 ModuleNotFoundError:没有名为'__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:


  • 来自proj.moduleB导入模块B

  • 您可以创建另一个脚本,例如 run.py ,从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天全站免登陆