Python - 如何使用复杂的目录结构PYTHONPATH?

时间:2010-07-14 17:59:14

标签: python pythonpath python-import

考虑以下文件\目录结构:

project\
|  django_project\
|  |  __init__.py
|  |  django_app1\
|  |  |  __init__.py
|  |  |  utils\
|  |  |  |  __init__.py
|  |  |  |  bar1.py
|  |  |  |  ...
|  |  |  ...
|  |  django_app2\
|  |  |  __init__.py
|  |  |  bar2.py
|  |  |  ...
|  |  ...
|  scripts\
|  |  __init__.py
|  |  foo.py
|  |  ...

我应该如何在 foo.py 中使用 sys.path.append ,以便我可以使用 bar1.py bar2的.py
导入的外观如何?

2 个答案:

答案 0 :(得分:2)

出于便携性原因,使用相对路径会更受欢迎。

foo.py脚本的顶部添加以下内容:

import os, sys
PROJECT_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)
sys.path.append(PROJECT_ROOT)

# Now you can import from the django_project package
from django_project.django_app1.utils import bar1
from django_project.django_app2 import bar2

答案 1 :(得分:1)

import sys
sys.path.append('/absolute/whatever/project/django_project/django_app1')
sys.path.append('/absolute/whatever/project/django_project/django_app2')

虽然您需要评估是否要在路径中同时使用两者 - 以防两者中存在竞争模块名称。在您的路径中最多只有django_project可能是有意义的,并在您需要时调用django_app1/bar1.py并在需要时调用import django_app2.bar2.whatever