Python从并行目录导入模块
我将如何组织我的python导入,以便有这样一个目录Python从并行目录导入模块,python,import,module,parent,relative-import,Python,Import,Module,Parent,Relative Import,我将如何组织我的python导入,以便有这样一个目录 project | \ | __init__.py | src | \ | __init__.py | classes.py | test \ __init__.py tests.py 然后在/project/test/tests.py内部可以导入classes.py 我在tests.py中有这样的代码 from .. src.classes import(
project
| \
| __init__.py
|
src
| \
| __init__.py
| classes.py
|
test
\
__init__.py
tests.py
然后在/project/test/tests.py内部可以导入classes.py
我在tests.py中有这样的代码
from .. src.classes import(
scheduler
db
)
我得到了错误的答案
SystemError: Parent module '' not loaded, cannot perform relative import
有人知道该怎么做吗?Python会将包含您启动的脚本的文件夹添加到PYTHONPATH中,因此如果您运行
python test/tests.py
只有文件夹test
被添加到路径中(而不是执行命令的基本目录)
而是像这样运行测试:
python -m test.tests
这将把base dir添加到python路径中,然后通过非相对导入可以访问类:
from src.classes import etc
如果您确实想使用相对导入样式,那么需要将3个目录添加到包目录中
package
* __init__.py
* project
* src
* test
您可以使用
python -m package.test.tests
另见:
test/
目录中有一个\uuu init\uuuu.py
。