[英]Python relative imports from parent directory
Here is the file structure I have:这是我的文件结构:
app/
main.py
folder/
a.py
b.py
In the file a.py
i have import b
, and in main.py
, i have import folder.a
.在文件
a.py
中,我有import b
,在main.py
中,我有import folder.a
。
When I run python3 a.py
from folder/
, everything works fine.当我从
folder/
运行python3 a.py
时,一切正常。 However when I run python3 main.py
from app/
, I get ModuleNotFoundError: No module named b
, which is caused by the import in a.py
但是,当我从
app/
运行python3 main.py
时,我得到ModuleNotFoundError: No module named b
,这是由a.py
中的导入引起的
I have found a way to avoid this, which is to simply put import folder.b
in a.py
, but this is not very satisfying, as I can no longer lauch a.py
from folder/
.我找到了一种避免这种情况的方法,就是简单地将
import folder.b
放在a.py
中,但这不是很令人满意,因为我无法再从folder/
启动a.py
What should i do for the import to work from both folder?我应该怎么做才能从两个文件夹导入? Please don't answer my question by saying i should modify my architecture, i've been looking for answers to this question on SO for 2 hours but i haven't found anything convincing.
请不要通过说我应该修改我的体系结构来回答我的问题,我一直在 SO 上寻找这个问题的答案 2 小时,但我没有找到任何令人信服的东西。
In a.py try:在 a.py 中尝试:
from folder import b
or:要么:
from folder.anotherfolder import b
or in main.py:或者在 main.py 中:
from folder import a, b
or:要么:
from folder.anotherfolder import a, b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.