The general answer to this question should be don't, I guess. Messing with relative paths means that the path is relative to the place from where you're calling it. That's why PYTHONPATH
is worth embracing instead.
Let's assume, your directory structure looks like this:
./projects/myproject/ElementExtractor.py
./projects/myproject/test/ElementExtractorTest.py
Now, you're calling your script like this:
[./projects/myproject]$ python3.5 ./test/ElementExtractorTest.py
Your current directory is myproject
and in ElementExtractorTest.py
you're adding ../
directory to sys.path
. This means, that ./projects/myproject/../
(i.e.: ./projects
) is effectively added to your PYTHONPATH. That' why Python is unable to locate your module.
Your code would work from test
directory though:
[./projects/myproject/test]$ python3.5 ./ElementExtractorTest.py
Now, by adding ..
to sys.path
you are effectively adding ./projects/myproject/test/../
(i.e. ./projects/myproject
) to sys.path
, so the module can be found and imported.