[英]Python3 ImportError: attempted relative import with no known parent package
I have the following 3 python files:我有以下 3 python 文件:
main.py
from .Constants import *
__init__.py
Constants.py
: Constants.py
:
CONSTANT_TEST = test
Now when I run python3 main.py
i get the following error现在,当我运行
python3 main.py
时,出现以下错误
ImportError: attempted relative import with no known parent package
Not sure what I am missing here.不知道我在这里错过了什么。
The general rule of thumb is that you should never execute files from within the same package. My suggestion would be to create a test file and import your package into that file, then do all of your testing from within that file.一般的经验法则是永远不要从同一个 package 中执行文件。我的建议是创建一个测试文件并将 package 导入该文件,然后从该文件中进行所有测试。 For example, if your package directory looks like this:
例如,如果您的 package 目录如下所示:
package_tests.py
package/
__init__.py
main.py
Constants.py
In package/__init__.py
:在
package/__init__.py
:
from package.Constants import CONSTANT_TEST
# import everything here that you want users to be able to access by topmost import ("import package")
In package/Constants.py
:在
package/Constants.py
中:
CONSTANT_TEST = "constant"
In package/main.py
:在
package/main.py
:
from package.Constants import CONSTANT_TEST
# other code that utilizes CONSTANT_TEST
In package_tests.py
:在
package_tests.py
中:
import package
print(package.CONSTANT_TEST)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.