Reputation: 2068
There are many questions with slight variations of this problem in SO. None of the answers I've seen solve my problem, so I'm asking a new question.
I have this folder structure:
/myapp/ \__init__.py modu1.py modu2.py
__init__.py
is empty
modu1.py
class TestMod1Class():
def msg(self):
print "Hello World!"
modu2.py
import myapp.modu1
obj = myapp.modu1.TestMod1Class()
obj.msg()
If from the directory /myapp/ I run python modu2.py
i get:
Traceback (most recent call last):
File "modu2.py", line 1, in <module>
import myapp.modu1
ImportError: No module named myapp.modu1
What I'm I doing wrong? I've read the docs, and still can't make sense of this.
Upvotes: 1
Views: 1558
Reputation: 388253
If from the directory /myapp/ I run
python modu2.py
i get
If you run a module directly, it does not run as part of a package it might belong to. As such importing myapp.modu1
will look for myapp/myapp/modu1.py
, which is obviously not where it is.
If you want the myapp
package to work, you have to start the execution from within the root directory. So add a main.py
next to the myapp
folder:
/main.py
/myapp
/__init__.py
/modu1.py
/modu2.py
And from there, you can do:
import myapp.modu2
And then you have to start with python main.py
.
Upvotes: 2
Reputation: 4810
You are already within the myapp
module by being in the myapp
folder. Therefore, you do not need to use the import myapp.modu1
syntax and instead should use import modu1
.
For example:
import modu1
obj = modu1.TestMod1Class()
obj.msg() # output: Hello World!
Note: I tested in Python 3 because I don't have 2 on my machine, but it should be the same (I did edit modu1 to use the new print
syntax).
Upvotes: 5