Import issue in python packages

Peter Otten __peter__ at web.de
Fri Aug 10 13:23:22 EDT 2018


Venkatesh Adiga wrote:

> Hi All,
> 
> I am facing issue with python package import.
> In my project, I have many directories with different python classes
> defined within them. I am trying to import those classes in another python
> program, but not able to import them.
> Here are my directories and file structures.
>   src/platform/operatingsys.py : Defined OperatingSystem Class
>   src/platform/ipc.py : Defined IPC class
>   src/platform/MyThread.py: Defined MyThread class
>   src/platform/__init__.py - zero sized file
> 
>   src/utils/abc.py
>   src/utils/def.py
>   src/utils/__init__.py
> 
>   src/api/xyz.py
>   src/api/__init__.py
> 
>   src/unittest/TestSuite.py - Defined UnitTest Class
>   src/unittest/__init__.py
>   src/__init__.py
> 
> 
> Now, I am trying to use the above classes in another python program(
> TestPackage.py) as below:
> 
> 
> *from src.platform.operatingsys import OperatingSystem*
> .....
> --------------
> Execution of TestPackage.py throws an error as below
> 
>  ImportError: No module named 'src'
> 
> Currently I have a working code which prefixes sys.path with every
> directory defined in the package list before import any classes.
> 
> sys.path.append("src/unittest/")
> import OperatingSystem
> 
> But I do not have the hard-coded path and append to sys.path variable.
> So my question is:
> 1)  Is there any better way of having the sys.path variable appended by
> directory listing?
> 2)  What changes i need to do so that my import statement looks like
> below:
>        *from src.platform.operatingsys import OperatingSystem*
> 
> Please suggest...

Ensure that src is in your PYTHONPATH, preferrably as an absolute path.
Then import the packages and modules without the src prefix, e. g.

sys.path.append("/path/to/src")
import platform.operatingsys

If you insist on src as part of the import the directory's parent needs to 
be in the path:

sys.path.append("/path/to")
import src.platform.operatingsys

Note that it's better to avoid manipulating sys.path from within your 
scripts. If at all possible install your packages or at least add .pth files 
or a PYTHONPATH environment variable.




More information about the Python-list mailing list