1

i have the following directory structure

project
  example
    module
      file1.py
      __init__.py
  test
    module
      test1.py
      __init__.py

i need to reuse the code in test1.py

in file1.py i am importing the module as

from test.module.test1 import MyClass

The code is working for me when i run in PyCharm since the content root is set. In case of terminal, i am able to run the example only when i set the PYTHONPATH to "/home/ubuntu/project" . i.e. my project folder.

If the path is not set am getting the following error

ModuleNotFoundError: No module named 'test.module'

The code is failing in CI. i dont have the control of setting up the PYTHONPATH before running file1.py.

Is there any way to fix it with python in file1.py (by setting some path).

I couldnt move the test code to a common place, since it is referenced in many placed.

srinath
  • 2,748
  • 6
  • 35
  • 56
  • 1
    I think some of the solutions here might be helpful: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder – Zaid Al Shattle Feb 25 '21 at 11:07
  • You need to add your upper directory to the path using `src.path.append('..')` or `src.path.append('../..')`. This way it will work across both scenarios. Or you can simply cd to project and run `python example/module/file1.py` – thethiny Feb 25 '21 at 11:21

0 Answers0