Import issue in python packages

Venkatesh Adiga rvadiga at gmail.com
Sat Aug 11 04:46:56 EDT 2018


Thanks Peter... What are the ways to update outside of the python program
without defining environment variable for source code path.... Otherwise
can I do it once in during initialization of sys.path update?


On Fri, 10 Aug 2018, 10:56 pm Peter Otten, <__peter__ at web.de> wrote:

> 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.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list