0

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?

Emilio Conte
  • 1,105
  • 10
  • 29
  • This doesn't answer your question directly, but why not a) run python setup.py develop (which will create your virtual links and add it to your path) and b) if you can't find your path as you want, does it have __init__.py in it? – Kelvin Dec 21 '16 at 15:09
  • 1
    How about something like: `os.path.dirname(os.path.abspath(__file__))`. This, or some variation, is what I usually use to get the path to the directory of a file/a project directory. – elethan Dec 21 '16 at 15:12
  • @elethan it was to avoid this imbricated os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) But this one works returning the same path – Emilio Conte Dec 21 '16 at 15:24
  • @Kelvin Thanks for your help. Of course there is an init file. But the problem came from that paths are already in sys when I import environ. So it's too late to fix it. – Emilio Conte Dec 21 '16 at 15:27

2 Answers2

0

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.

Emilio Conte
  • 1,105
  • 10
  • 29
0

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]:
Kelvin
  • 1,357
  • 2
  • 11
  • 22