你能告诉我如何正确地进行相对导入吗?
项目结构:
p1
|- x1
| |- __init__.py
| |- x1_module1.py
|- x2
|- __init__.py
|- x2_module1.py
在 x2_modules.py
try:
from p1.x1.x1_module import temp_func
except Exception as e:
print('Failed "from p1.x1.x1_module import temp_func"')
print(e)
try:
from .x1.x1_module import temp_func
except Exception as e:
print('Failed "from .x1.x1_module import temp_func"')
print(e)
try:
from ..x1.x1_module import temp_func
except Exception as e:
print('Failed "from ..x1.x1_module import temp_func"')
print(e)
输出:
Failed "from p1.x1.x1_module import temp_func"
No module named 'p1'
Failed "from .x1.x1_module import temp_func"
attempted relative import with no known parent package
Failed "from ..x1.x1_module import temp_func"
attempted relative import with no known parent package
[Finished in 0.2s]