[英]Working around "ModuleNotFoundError: ...'__main__' is not a package" error
I've got a project running on a server with the structure我有一个在具有结构的服务器上运行的项目
proj
__init__.py
module_a.py
module_b.py
main.py
And in the header of main.py, I import from other modules with the format在 main.py 的 header 中,我从其他模块导入格式
from .module_a import func1
from .module_b import func2
This runs fine on the server, but when I'm testing things on my local machine it raises the error:这在服务器上运行良好,但是当我在本地机器上测试时,它会引发错误:
ModuleNotFoundError: No module named '__main__.module_a'; '__main__' is not a package
There have been a lot of questions asked regarding this error and the accepted solution is almost always to replace the import statement with关于这个错误已经提出了很多问题,并且接受的解决方案几乎总是将导入语句替换为
from proj.module_a import func1
Is there something I can do to configure my local environment to allow this type of syntax without having a completely different set of import statements depending on whether the code is running locally or remotely?我可以做些什么来配置我的本地环境以允许这种类型的语法,而无需根据代码是在本地运行还是远程运行而使用完全不同的导入语句集?
Keep your imports relative, without using the package full path, so that you have the flexibility of renaming it as you wish, like in保持你的导入相对,而不使用 package 完整路径,这样你就可以灵活地重命名它,就像在
from .module_a import func1
Then in your local environment, change your current dir to the proj
parent folder and run:然后在您的本地环境中,将当前目录更改为
proj
父文件夹并运行:
python -m proj.main
An alternative would be to rename main.py
to __main__.py
and then just writing另一种方法是将
main.py
重命名为__main__.py
然后只写
python -m proj
will do.会做。 But that may affect the behaviour on the server if you copy the files as is.
但如果您按原样复制文件,这可能会影响服务器上的行为。
Packages are usually to be imported.通常要导入包。 This is a common problem when we start running from arbitrary scripts located inside the package (in this case
main.py
).当我们从位于 package(在本例中
main.py
)中的任意脚本开始运行时,这是一个常见问题。 If the package is simply imported from outside, everything works.如果简单地从外部导入 package,一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.