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

Python-如何使用复杂的目录结构创建PYTHONPATH?,python,pythonpath,python-import,Python,Pythonpath,Python Import,考虑以下文件\目录结构: project\ | django_project\ | | __init__.py | | django_app1\ | | | __init__.py | | | utils\ | | | | __init__.py | | | | bar1.py | | | | ... | | | ... | | django_app2\ | | | __init__.py | | | bar2.py | |

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

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.pybar2.py
导入的将是什么样子

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

尽管您需要评估是否希望在路径中同时包含这两个模块,以防两者中都有相互竞争的模块名。路径中最多只能有
django_项目
,需要时调用
django_app1/bar1.py
,需要时调用
import django_app2.bar2。无论什么

出于可移植性的原因,使用相对路径会更可取

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