我是Python新手,我试图理解一个问题,我在创建包时看到了这个问题。我有以下文件结构:(Working-Directory is /my/Python/jmLib2)
/my/Python/jmLib2
|--- Phone
| |--- __init__.py
| |--- Pots.py
|- Test2.py
---------------------------------
cat ./jmLib2/Pots.py
#!/usr/bin/python
def Pots():
print ("I'm Pots Phone")
---------------------------------
cat ./jmLib2/__init__.py
from Pots import Pots
---------------------------------
cat ./Test2.py
#!/usr/bin/python
from Phone import Pots
import os.path
print ("OS:"+str(os.path))
Pots()当我现在这么做的时候:
python2 Test2.py
OS:<module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>
I'm Pots Phone*GREAT...BUT,如果我这么做了:
python3 Test2.py
Traceback (most recent call last):
File "Test2.py", line 2, in <module>
from Phone import Pots
File "/home/juergen/my/Python/jmLib2/Phone/__init__.py", line 1, in <module>
from Pots import Pots
ImportError: No module named 'Pots'我正在使用Eclipse下的PyDev。PyDev在init.py文件中报告了一个“未解决的导入: Pots"-error。在PyDev和bash下,我也有同样的追溯问题。
再说一次,我对Python很陌生.所以这也许是一个非常愚蠢的错误。但是有人能解释一下python2和python3.4之间的区别吗?我必须修改PYTHONPATH吗?为什么?
朱尔根问候
发布于 2015-12-25 10:25:22
TL;DR: 相对进口消失了.使用绝对导入代替。
要么使用:
from Phone.Pots import Pots或者:
from .Pots import Pots出现这个问题是因为Pots是Phone包的一部分:没有名为Pots的模块,有一个名为Phone.Pots的模块。
Python2有一个名为https://docs.python.org/2/tutorial/modules.html#intra-package-references的特性,允许您编写import Pots,即使这在技术上是不正确的。
然而,相对进口是问题与困惑的一个来源。
Phone.Pots,但我可以使用import Pots?这是非常不一致的。出于这些原因,从Python 3中删除了相对导入。
您可以使用导入从Python2摆脱相对导入。
from __future__ import absolute_importhttps://stackoverflow.com/questions/34461987
复制相似问题