I currently have a python project with multiple apps and numerous support modules. The apps have dependencies on the support modules. This project is used on different host.
RootPath
├───module1
├───module2
├───App
│ ├───main.py
│ └───lib.py
└───App2
├───main.py
└───lib.py
I find the path of the root directory in each main.py and do a sys.path.extend()
so that main.py is able to import all dependencies.
while os.path.basename(path) != "RootPath":
old_path = path
path = os.path.dirname(old_path)
# Exit if directory not found
if path == old_path:
raise Exception("Could not find RootPath directory. Ended search at '{0}'".format(path))
sys.path.extend([path + "module1", path + "module2"])
This has worked well for me but I'm finding this doesn't seem scalable for a few reasons.
- Every time I introduce a new app, I'll need to copy and paste this code.
- Every time I want to test a module by running it directly (i.e module.py) and if module.py depends on module2.py, I will need to copy the same logic into module.py.
I think I can solve this if I have an init script that adds the correct paths directly into PYTHONPATH. How can I add paths to PYTHONPATH. I'm using this project in windows.