从父目录的子目录导入python模块
我有一个这样的目录结构从父目录的子目录导入python模块,python,python-import,Python,Python Import,我有一个这样的目录结构 dir1/subdir1/module1.py dir1/subdir2/subdir22/module2.py 假设我正在向每个目录和子目录添加_init__uu.py。我想从模块2中导入模块1,在参考了相关问题并尝试了不同的方法后,我找不到解决方案。比如说 在模块2中,我尝试导入模块1,如 from .... import subdir1.module1 from ....subdir1 import module1 上述两种导入都会引发语法错误。这对我来说很有效
dir1/subdir1/module1.py
dir1/subdir2/subdir22/module2.py
假设我正在向每个目录和子目录添加_init__uu.py。我想从模块2中导入模块1,在参考了相关问题并尝试了不同的方法后,我找不到解决方案。比如说
在模块2中,我尝试导入模块1,如
from .... import subdir1.module1
from ....subdir1 import module1
上述两种导入都会引发语法错误。这对我来说很有效:
$ mkdir -p dir1/subdir1
$ mkdir -p dir1/subdir2/subdir22
$ touch dir1/{,subdir1,subdir2,subdir2/subdir22}/__init__.py
$ echo 'x = 42' > dir1/subdir1/module1.py
$ echo 'from ...subdir1.module1 import x; print x' > dir1/subdir2/subdir22/module2.py
$ python -m dir1.subdir2.subdir22.module2
42
魔法咒语是
from ...subdir1.module1 import x
虽然
from ...subdir1 import module1
也可以工作。以下代码可以从路径加载模块,即使不在包内或不在默认路径上(此处的模块是
Premission
我的引擎),但您应该在该文件夹中有一个虚拟\uu init\uuuuuuuuuuuuuuuuuuuuuy.py
文件:
import imp
ContemplateModulePath = os.path.join(os.path.dirname(__file__), '../src/python/')
try:
ContemplateFp, ContemplatePath, ContemplateDesc = imp.find_module('Contemplate', [ContemplateModulePath])
Contemplate = getattr( imp.load_module('Contemplate', ContemplateFp, ContemplatePath, ContemplateDesc), 'Contemplate' )
except ImportError as exc:
Contemplate = None
sys.stderr.write("Error: failed to import module ({})".format(exc))
finally:
if ContemplateFp: ContemplateFp.close()
if not Contemplate:
print ('Could not load the Contemplate Engine Module')
sys.exit(1)
else:
print ('Contemplate Engine Module loaded succesfully')
这对我很有效
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.dirname(path.dirname(path.abspath(__file__))) ) ) )
from dir1.subdir1 import module1
在第二节中,你有
模块1
而不是模块1
。。。看看