I am using python 2:
python --version
Python 2.7.13 :: Continuum Analytics, Inc.
I have the following project structure:
.
└── foo
├── bar1
│ ├── __init__.py
│ └── mod1.py
├── bar2
│ ├── __init__.py
│ └── mod2.py
├── __init__.py
└── start.py
start.py
from foo.bar2.mod2 import mod2_f
mod2_f()
mod1.py
def mod1_f():
print "mod1_f"
mod2.py
from foo.bar1.mod1 import mod1_f
def mod2_f():
mod1_f()
print "mod2_f"
If I run start.py from an IDE things work ok.
However using something like this:
python ./foo/start.py
results in
Traceback (most recent call last):
File "./foo/start.py", line 1, in <module>
from foo.bar2.mod2 import mod2_f
ImportError: No module named foo.bar2.mod2
Now, let's say I change the imports to
start.py
from bar2.mod2 import mod2_f
mod2_f()
mod2.py
from bar1.mod1 import mod1_f
def mod2_f():
mod1_f()
print "mod2_f"
Now things work from the command line python ./foo/start
However, PyCharm complains. why these differences?
foo
is the directory which contains everything, includingstart.py
So when from
start.py
you do thispython looks for a
foo
module (foo
is a module because it contains__init__.py
), which too high in your directory structure. I suppose it works from the IDE because IDE adds every module directory to pythonpath. But not from command line it doesn't.simple fix since
bar2
is a directory at the same level asstart.py
:note that
from
works differently in python 3. See ImportError on python 3, worked fine on python 2.7, that's probably why PyCharm complains when fixing the import line. You should configure PyCharm so it uses Python 2 and not Python 3 for it to work, or just drop thefrom
syntax altogether and do: