Subpackages and relative imports in PyCharm

2019-02-25 12:08发布

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?

1条回答
虎瘦雄心在
2楼-- · 2019-02-25 12:43

foo is the directory which contains everything, including start.py

So when from start.py you do this

from foo.bar2.mod2 import mod2_f

python 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 as start.py:

from bar2.mod2 import mod2_f

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 the from syntax altogether and do:

import bar2.mod2.mod2_f
查看更多
登录 后发表回答