[英]How to fix import sibling packages/modules in Python?
I have this file structure我有这个文件结构
.
└── sample
├── one
│ ├── __init__.py
│ └── util.py
└── two
├── __init__.py
└── test.py
Here is the content of util.py这是util.py的内容
def isOk():
return True
Here is the content of test.py这是test.py的内容
from sample.one import util
Whenever I'm inside the [two] folder and I type每当我在 [two] 文件夹中并输入
python test.py
I get我明白了
Traceback (most recent call last):
File "test.py", line 1, in <module>
from sample.one import util
ModuleNotFoundError: No module named 'sample'
How is that possible when I create all folders and __init__.py
by the book?当我按书创建所有文件夹和__init__.py
时,这怎么可能?
It seems that a method to invoke it might be似乎调用它的方法可能是
python -m two.test
If one
and two
are both subpackages of sample
, then you should add a sample/__init__.py
which may be empty.如果one
和two
都是sample
的子包,那么你应该添加一个sample/__init__.py
,它可能是空的。
If you then invoke python -m sample.two.test
from the right directory, it should work.如果然后从正确的目录调用python -m sample.two.test
,它应该可以工作。
You could even add package-relative imports like this:你甚至可以像这样添加与包相关的导入:
# test.py
from ..one import util
Please add the dir path to your PYTHONPATH请将目录路径添加到您的 PYTHONPATH
export PYTHONPATH=/PATH/TO/DIR/WHICH/CONTAINS/SAMPLE
2 real nice links to go through are: go 的 2 个真正不错的链接是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.