1

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.

  1. Every time I introduce a new app, I'll need to copy and paste this code.
  2. 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.

tyleax
  • 1,556
  • 2
  • 17
  • 45
  • 1
    When reading the dupe, please ignore the accepted answer, and go to the [top voted answer](https://stackoverflow.com/a/50193944/674039). – wim Mar 15 '19 at 18:19
  • @wim Thanks, that points me in the right direction. – tyleax Mar 15 '19 at 18:46

0 Answers0