0

I have been facing a weird situation for some months now.

In the several codes I have been working, to import a module in python 3.6.9, Ubuntu 18.04, such as:

import src.Modules.ABC.DC as DC

I do need to include sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..')) but all my colleges at work using the same code and virtual environment just does not need that line.

If it helps, in the terminal, if I do not include that line it returns:

ModuleNotFoundError: No module named 'src'

Consequently, my questions are:

1-Why do I need to include that line and in a different computer I does not need?

2-Do you suggested to always include that line to have a more reliable code?

The folder structure is something like:

Myproject/src/Modules/ABC/DE

Myproject/tests/Modules/ABC/test_DE

I created a virtual env at Myproject, at src, tests and so on. And it returns always the same. When I run without a venv it also returns the same problem. The python command I use is

python3 tests/Modules/ABC/test_DE.py

This is just annoying since I always need to remove that line to request a merge.

Crocco13
  • 3
  • 1

1 Answers1

3

Just set the PYTHONPATH environment variable to (the full path to) Myproject. That tells Python where to find modules to import, and it works regardless of which directory you run the script from. This avoids the need to modify sys.path.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thank you! It helps to solve the problem. I used the following procedure to change the virtual env PYTHONPATH https://stackoverflow.com/questions/4757178/how-do-you-set-your-pythonpath-in-an-already-created-virtualenv – Crocco13 Mar 05 '20 at 13:02
  • One aspect that keeps intriguing me is, that when I run `echo $PYTHONPATH` in their computer it does not return the path to the modules. – Crocco13 Mar 05 '20 at 13:07