3

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?

Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

2 Answers2

3

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
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
1
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
  • 7,680
  • 1
  • 35
  • 47