如果我在python中有以下文件结构:
directory1
├── directory2
│ └── file2
└── file1其中目录2是目录1的子目录,假设两者都不是软件包,那么如何从file2引用file1模块(假设我使用的是sys.path )?假设我在文件1中有x=1,并且我想在file2中打印出x的值,我会在文件2中使用什么导入语句?
发布于 2013-01-28 10:29:50
如果directory1和directory2在sys.path中都是绝对路径,不管其中一个是另一个的子目录,那么您可以用简单的语句导入这两个文件(我假设它们至少以.py扩展名命名):
# in file 1:
import file2
# in file 2:
import file1然后,您可以像往常一样访问内容:
# in file 2
import file1
print file1.x如果您需要在file2中设置sys.path,则使用类似以下内容:
# in file 2
import sys
import os.path
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,path)
import file1
print file1.x发布于 2013-01-28 10:29:09
└── directory1
├── directory2
│ └── file2.py
└── file1.py$ cat目录1/file1.py
x=1$ cat目录1/directory2/file2.py
import sys
from os.path import dirname, realpath
sys.path.append(dirname(realpath(__file__)) + '/..')
sys.path.append('..')
from file1 import x
print x$ python directory1/directory2/file2.py
1https://stackoverflow.com/questions/14554576
复制相似问题