从父目录的子目录导入python模块

时间:2015-05-12 22:07:53

标签: python python-import

我有一个像这样的目录结构

dir1/subdir1/module1.py
dir1/subdir2/subdir22/module2.py

假设我正在为每个目录添加__init__.py和子目录。我想从模块2导入module1,在引用相关问题并尝试不同的方法后,我找不到解决方案。例如

模块2中的

我试图导入模块1,如

from .... import subdir1.module1
from ....subdir1 import module1

以上导入都会引发语法错误。

3 个答案:

答案 0 :(得分:0)

This works for me:

SERVER ERROR: Connection timed out url=https://repo1.maven.org/maven2/org/scalamacros/quasiquotes_2.10/2.0.1/quasiquotes_2.10-2.0.1.pom.sha1

The magic incantation is

$ 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

though

from ...subdir1.module1 import x

also works.

答案 1 :(得分:0)

The following code can load a module from a path even if not inside a package or not on default path (module here is def Tm_weight(self): if self.temp == options.optTm: self.temp_weight = 100 elif self.temp > options.optTm: self.slope = (10-100)/(options.maxTm - options.optTm) self.inter = (100 - ((10-100)/(options.maxTm - options.optTm))*(options.optTm)) self.temp_weight = ((self.slope)*(self.temp) + (self.inter)) else: self.slope = (100 - 10)/(options.optTm - options.minTm) self.inter = (100 - ((100 - 10)/(options.optTm - options.minTm))*(options.optTm)) self.temp_weight = ((self.slope)*(self.temp) + (self.inter)) return self.temp_weight an engine of mine), you should have an dummy Contemplate file in that folder though:

__init__.py

答案 2 :(得分:0)

这对我有用,

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