Adding a path to the system using environ module

262 views Asked by At

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?

2

There are 2 answers

0
Emilio Conte On BEST ANSWER

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.

1
Kelvin On

If you are trying to get relative paths how about:

os.path.join("..", "..", __file__)

(Slightly different due to terminal)

In [1]: import os

In [3]: os.getcwd()
Out[3]: 'c:\\Temp\\foo\\bar'

In [4]: os.path.abspath(os.path.join('..','..',__name__))
Out[4]: 'c:\\Temp\\__main__'

In [5]: