问题
I am new to Python and I am trying to understand a problem, which I see when creating a package. I have the following file structure: (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()
When I now do:
python2 Test2.py
OS:<module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>
I'm Pots Phone*
GREAT...BUT, if I do:
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'
I am working with PyDev under Eclipse. PyDev reports me inside the init.py file an "Unresolved import: Pots"-error. I have the same traceback-problem under PyDev and bash.
Again, I am new to Python... so it is maybe a very stupid mistake. But can someone explain me, the difference between python2 and python3.4? Do I have to modify the PYTHONPATH? Why?
Greetings Juergen
回答1:
TL;DR: Relative imports are gone. Use absolute imports instead.
Either use:
from Phone.Pots import Pots
or:
from .Pots import Pots
The problem occurs because Pots
is part of the Phone
package: there is no module named Pots
, there's a module named Phone.Pots
.
Python 2 had a feature called relative imports that let you write import Pots
even if that was not technically correct.
Relative imports however are a source of problems and confusion:
- Who reads the code cannot immediately say whether the import is from a package or not.
- How come the module is named
Phone.Pots
, but I can useimport Pots
? This is highly inconsistent. - What if the submodule shadows a name of another module?
For these reasons, relative imports were removed from Python 3.
You can get rid of relative imports from Python 2 by using a __future__ import:
from __future__ import absolute_import
来源:https://stackoverflow.com/questions/34461987/python3-importerror-no-module-named-xxxx