问题描述
我正在使用 python 2:
python --versionPython 2.7.13 :: Continuum Analytics, Inc.
我有以下项目结构:
.└── 噗├── bar1│ ├── __init__.py│ └── mod1.py├── bar2│ ├── __init__.py│ └── mod2.py├── __init__.py└── start.pystart.py
from foo.bar2.mod2 import mod2_fmod2_f()
mod1.py
def mod1_f():打印mod1_f"
mod2.py
from foo.bar1.mod1 import mod1_fdef mod2_f():mod1_f()打印mod2_f"
如果我从 IDE 运行 start.py,一切正常.
但是使用这样的东西:
python ./foo/start.py
结果
回溯(最近一次调用最后一次):文件./foo/start.py",第 1 行,在 <module> 中从 foo.bar2.mod2 导入 mod2_f导入错误:没有名为 foo.bar2.mod2 的模块
现在,假设我将导入更改为
start.py
from bar2.mod2 import mod2_fmod2_f()
mod2.py
from bar1.mod1 import mod1_fdef mod2_f():mod1_f()打印mod2_f"
现在从命令行开始工作 python ./foo/start
然而,PyCharm 抱怨.为什么会有这些差异?
foo
是包含所有内容的目录,包括 start.py
所以当你从 start.py
做这个
from foo.bar2.mod2 import mod2_f
python 查找 foo
模块(foo
is 是一个模块,因为它包含 __init__.py
),在您的目录结构中太高了.我想它可以从 IDE 运行,因为 IDE 将每个模块目录添加到 pythonpath.但不是从命令行它没有.
简单修复,因为 bar2
是与 start.py
处于同一级别的目录:
from bar2.mod2 import mod2_f
请注意,from
在 python 3 中的工作方式不同.请参阅 python 3 上的导入错误,在 python 2.7 上运行良好,这可能就是 PyCharm 在修复导入行时抱怨的原因.您应该配置 PyCharm 以便它使用 Python 2 而不是 Python 3 使其工作,或者完全删除 from
语法并执行:
import bar2.mod2.mod2_f
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, 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
这篇关于PyCharm 中的子包和相关导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!