Python - How PYTHONPATH with complex directory structure?

Consider the following structure of the \ directory file:

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 to use sys.path.append in foo.py so that I can use bar1.py and bar2.py ?
What does import look like?

+2
source share
2 answers

The use of 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 
+2
source
 import sys sys.path.append('/absolute/whatever/project/django_project/django_app1') sys.path.append('/absolute/whatever/project/django_project/django_app2') 

Although you need to evaluate whether you want to have it in your way, as well as if in both cases there are names of competing modules. It might make sense to 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.

+1
source

Source: https://habr.com/ru/post/1442862/


All Articles