views:

39

answers:

2

Consider the following file\directory structure:

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
|  |  ...

How should I use sys.path.append in foo.py so that I could use bar1.py and bar2.py?
How would the import look like?

+1  A: 
import sys
sys.path.append('/absolute/whatever/project/django_project/django_app1')
sys.path.append('/absolute/whatever/project/django_project/django_app2')

Though you need to evaluate whether you want to have both in your path -- in case there are competing module names in both. It might make sense to only have up to django_project in your path, and call django_app1/bar1.py when you need it and import django_app2.bar2.whatever when you need it.

eruciform
+1  A: 

Using relative paths would be much more desirable for portability reasons.

At the top of your foo.py script add the following:

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
sdolan