pythonenviron

Adding a path to the system using environ module


In a setting file I append a path to the system hardcoding the url like this:

sys.path.append('/home/user/path/to/projectdir')

It works.

As soon as I want to make it relative, it fails even if I retrieve the exact path with environ module.

import environ

ROOT_DIR = environ.Path(__file__) - 3
sys.path.append(ROOT_DIR.path())

To me the incredible thing is that print(ROOT_DIR.path()) outputs the exact url of project_dir.

print(ROOT_DIR.path())
> '/home/user/path/to/projectdir'

Here is the tree of my project.

project_dir
└── soloscrap
    └── soloscrap
        ├── settings.py

How could I add this path then? Isn't it weird?


Solution

  • I suppose that environ arrives too late and the paths are already fixed. So the solution seems to be something like this:

    SYSPATH = os.path.dirname(
        os.path.dirname(
            os.path.dirname(
                os.path.abspath(__file__)
            )
        )
    )
    
    sys.path.append(SYSPATH)
    

    Which is not elegant.