Python sys.path

Python sys.path,python,Python,如果我有以下python文件结构: directory1 ├── directory2 │   └── file2 └── file1 如果目录2是目录1的子目录,并且假设两者都不是包,那么在使用sys.path的情况下,如何从文件2中引用文件1模块?假设文件1中有x=1,并且我想在文件2中打印出x的值,那么我在文件2中会使用什么导入语句 └── directory1 ├── directory2 │   └── file2.py └──

如果我有以下python文件结构:

    directory1
    ├── directory2
    │   └── file2
    └── file1
如果目录2是目录1的子目录,并且假设两者都不是包,那么在使用sys.path的情况下,如何从文件2中引用文件1模块?假设文件1中有x=1,并且我想在文件2中打印出x的值,那么我在文件2中会使用什么导入语句

└── directory1
    ├── directory2
    │   └── file2.py
    └── file1.py
$cat目录1/file1.py

x=1
$cat directory1/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

1

如果directory1和directory2都在
sys.path
中作为绝对路径,而不管其中一个是另一个的子目录,那么您可以使用简单语句导入这两个文件(我假设它们的名称至少扩展名为.py):

然后您可以像往常一样访问内容:

# 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

通常情况下,我们鼓励您不要做这种事情,而是要有一个严格的模块层次结构/组合,其中顶级模块只依赖于与它们自己的目录或python模块路径平行或较低的模块。但是,您如何使用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