问题描述
能否请您告诉我如何正确进行相对导入。
项目结构:
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]
要了解更多信息,请查看以下图片:
解决方法
项目结构:
p1
|- x1
| |- __init__.py
| |- x1_module1.py
|- x2
|- __init__.py
|- x2_module1.py
编辑:该代码未遵循PEP-8,并且很难阅读。因此,我对其进行了优化。
请尝试以下代码:
import sys
import os
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(
os.path.realpath(
os.path.join(
os.getcwd(),os.path.expanduser(__file__)
)
)
)
sys.path.append(
os.path.normpath(
os.path.join(
SCRIPT_DIR,PACKAGE_PARENT
)
)
)
from x1.x1_module import tempfunction
可行works
问候 伊桑·卡普尔(Ishaan Kapoor)
,如果您的python脚本是从p1目录中调用的,那么这应该可以:
from x1.x1_module1 import temp_func
要查看python在哪里搜索您的模块的列表,请使用以下命令:
import sys
print(sys.path)
sys.path的第一项应该是脚本运行所在的目录,我假设它是p1