1
     common/src/validation/file1.py

In the common/src/validation/ and common/src/ folder "_init_" is defined.

     common/test/validation/file2.py
     common/test/validation/case/file3.py

In file2.py and file3.py, I want to import class from file1.py.

Im giving the following line in file2.py and file3.py.:

      from file1 import class1  

I currently get error:

      #ImportError: No module named file1

what should be the sys.path.append ?

abcde
  • 85
  • 1
  • 2
  • 7
  • 1
    Possible duplicate of [Python: import a file from a subdirectory](http://stackoverflow.com/questions/1260792/python-import-a-file-from-a-subdirectory) – Torxed Nov 18 '15 at 11:29

2 Answers2

0

You can basically just change PYTHONPATH to common and run from there. Then reference all import paths in relation to that.

like so: (assuming you are in common and your main is in file3.py)

PYTHONPATH=. python test/validation/case/file3.py

Make sure to have __init__.py files in any directory you import (the content of this file doesn't matter)

I usually like putting in the root of every project a run.sh file with some version of this line (pointing to wherever my main func is) in it.

It will usually contain a simple something like that:

#!/bin/bash
source some_env/bin/activate # start the relevant environment if you have one
PYTHONPATH=. python src/main.py # set PYTHONPATH and run
deactivate # exit the relevant environment if started one

Another option is to do this but is't not as elegant.

Community
  • 1
  • 1
daTokenizer
  • 96
  • 1
  • 9
  • IS there a way without using the PYTHONPATH ? I would like to use sys.path.append... – abcde Nov 18 '15 at 11:51
  • check the link in the end of the answer.. [here it is again](http://stackoverflow.com/questions/3488548/python-module-importing-issues?rq=1) – daTokenizer Nov 18 '15 at 12:31
0

If you want to import a file from a folder you should have a file named

__init__.py 

in that folder (it could also be a blank file).

toti08
  • 2,448
  • 5
  • 24
  • 36