简体   繁体   English

PyCharm中的子包和相关进口

[英]Subpackages and relative imports in PyCharm

I am using python 2: 我正在使用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 start.py

from foo.bar2.mod2 import mod2_f
mod2_f()

mod1.py mod1.py

def mod1_f():
    print "mod1_f"

mod2.py 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. 如果我从IDE运行start.py就可以了。

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 start.py

from bar2.mod2 import mod2_f
mod2_f()

mod2.py 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. 现在事情可以从命令行python ./foo/start但是,PyCharm抱怨道。 why these differences? 为何这些差异?

foo is the directory which contains everything, including start.py foo是包含所有内容的目录,包括start.py

So when from start.py you do this 所以当你从start.py这样做时

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. python寻找一个foo模块( foo 一个模块,因为它包含__init__.py ),它在你的目录结构中太高了。 I suppose it works from the IDE because IDE adds every module directory to pythonpath. 我认为它适用于IDE,因为IDE将每个模块目录添加到pythonpath。 But not from command line it doesn't. 但不是从命令行它没有。

simple fix since bar2 is a directory at the same level as start.py : 简单修复,因为bar2是一个与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. 注意, from不同的python 3.看作品导入错误的蟒蛇3,运行良好的Python 2.7版 ,这可能就是PyCharm固定导入线时抱怨。 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: 您应该配置PyCharm,因此它使用Python 2而不是Python 3来使用它,或者只是完全删除from语法并执行:

import bar2.mod2.mod2_f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM