想象一下,我有这样的结构:
dir/
__init__.py
dir1/
__init__.py
x.py
dir2/
__init__.py
y.py
现在我想将x.py导入y.py。
我在PEP 328的y.py中尝试此from ..dir1.x import *
,但我收到此错误Attempted relative import in non-package
。
我搜索了几个小时,但我找不到任何答案
像我这样有很多类似的问题,但没有一个像this那样帮助我
请帮忙。
非常感谢。
答案 0 :(得分:0)
直接调用文件时,相对导入将无效:
python y.py
因为他们有__name__ == '__main__'
而不是他们的完整包名。
要进行相对导入,您必须使用y
作为包:
python -m dir.dir2.y
答案 1 :(得分:0)
在y.py
中,添加这段导入代码
import sys
sys.path.insert(0, '..')
然后做
from dir1.x import *