2

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

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导入 会是什么样子?

4

2 回答 2

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
于 2010-07-14T18:15:15.960 回答
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仅在您的路径中设置 up 并django_app1/bar1.py在您需要它和需要它时调用它可能是有意义的import django_app2.bar2.whatever

于 2010-07-14T18:08:33.373 回答