简体   繁体   中英

python Import module from a different directory structure

     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 ?

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM