Python - 如何在复杂目录结构中设置PYTHONPATH?
考虑一下下面这个文件和目录的结构:
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?
那样的 import 语句应该是什么样的呢?
2 个回答
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
来引入。
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