I know this question has been asked many times here and I'v probably read most of the answers (including this and that) as well as the python documentation but still can not find an answer to my very simple import problem. It's so simple that I must miss something stupid but I don't see it yet. I have setup the following structure:
myproject
myscript.py
MyPackage
__init.py__
mymodule.py
I just want to load mymodule.py from myscript.py (or the commandline python interpreter which should be the same).
myscript.py contains:
#!/usr/bin/python
import MyPackage
__init.py__ contains:
from . import mymodule
mymodule.py contains
#!/usr/bin/python
def myfunction():
print "mymessage"
My goal is to call myfunction from myscript.py but if I try to call the module I get
$python myscript.py
Traceback (most recent call last):
File "myscript.py", line 2, in <module>
import MyPackage
ImportError: No module named MyPackage
What I already tried:
- I tried everything under OSX and Ubuntu Linux to reduce the possibility of a faulty python installation.
- I set the
PYTHONPATHenvironment variable to themyprojectdirectory as well as to.and to both. - I left
__init.py__blank - I tried the import statements also from the python interpreter started from the
myprojectdirectory I tried the following import statements:
from MyPackage import mymodule import MyPackage.mymodule import MyPackage.mymodule as moduleall without success (same error message).
If I put mymodule.py in the project directory without using a package, import works fine. But I don't see why the import from the subpackages is not working.
Any idea how I can get that to work?
Thanks for help!
myprojectdirectory is listed insys.path. Before importingMyPackage, doessys.pathcontain the right directory?import sysandprint sys.pathit shows a list containint the path of the "myproject" directory correctly:['', '/Users/michael/Entwicklung/python/myproject', ... ]__init__.py. Could you try that again, but make sure you remove all*.pycfiles. Perhaps add a singleprint "imported"line in__init__.py.