Suppose I have a project in the following structure
projectfoo/
|- mymodule/
|--|- __init__.py
|--|- library.py
|- preprocessor.py
and in the __init__.py
in mymodule
looks like this
from . import library #library itself has other functions
def some_function():
blar blar blar...
and the preprocessor.py
would look like follows
import mymodule
def main():
something()
def something():
mymodule.some_function() # calls the function defined in __init__.py
if __name__ == '__main__':
main()
Then I started projectbar
, which is using a lot of common code from projectfoo
. So instead of copying and pasting code between projects, I wish to import projectfoo
into project bar, as follows.
projectbar/
|- projectfoo/
|--|- mymodule/
|--|--|- __init__.py
|--|--|- library.py
|--|- preprocessor.py
|- index.py
So I am trying to import preprocessor
in my index.py
as follows
from projectfoo import preprocessor
However I am getting an error saying preprocessor.py
is now unable to import mymodule
.
ImportError: No module named 'mymodule'
Am I doing this correctly? I am using python3.4 running in ubuntu 14.04 in my setup.
EDIT: I also tried adding __init__.py
to projectfoo
, but I am still getting the same error
You are getting this error because you did not added the path of preprocessor as a library package
from sys import path as pylib #im naming it as pylib so that we won't get confused between os.path and sys.path
import os
pylib += [os.path.abspath(r'/projectfoo')]
from projectfoo import preprocessor
FYI: os.path will return the absolute path. but sys.path will return the path env. variable in system settings.
Hope it helps.