Subpackages and relative imports in PyCharm

南楼画角 提交于 2019-12-20 02:09:22

问题


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:


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


来源:https://stackoverflow.com/questions/45954981/subpackages-and-relative-imports-in-pycharm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!