Python - 如何在复杂的目录结构中设置PYTHONPATH?

3
考虑以下文件/目录结构:
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 应该是什么样子的?

2个回答

3

出于可移植性的原因,使用相对路径更为理想。

在你的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
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接