我想明白了。非常令人沮丧,尤其是来自python2。
你必须加上a。对于模块,不管它是相对的还是绝对的。
我创建的目录设置如下所示。
/main.py
--/lib
--/__init__.py
--/mody.py
--/modx.py
modx.py
def does_something():
return "I gave you this string."
mody.py
from modx import does_something
def loaded():
string = does_something()
print(string)
main.py
from lib import mody
mody.loaded()
当我执行main时,会发生这样的事情
$ python main.py
Traceback (most recent call last):
File "main.py", line 2, in <module>
from lib import mody
File "/mnt/c/Users/Austin/Dropbox/Source/Python/virtualenviron/mock/package/lib/mody.py", line 1, in <module>
from modx import does_something
ImportError: No module named 'modx'
我运行2to3,核心输出是这样的
RefactoringTool: Refactored lib/mody.py
--- lib/mody.py (original)
+++ lib/mody.py (refactored)
@@ -1,4 +1,4 @@
-from modx import does_something
+from .modx import does_something
def loaded():
string = does_something()
RefactoringTool: Files that need to be modified:
RefactoringTool: lib/modx.py
RefactoringTool: lib/mody.py
我不得不修改modi .py的import语句来修复它
try:
from modx import does_something
except ImportError:
from .modx import does_something
def loaded():
string = does_something()
print(string)
然后我再次运行main.py,得到了预期的输出
$ python main.py
I gave you this string.
最后,清理一下,让它在2和3之间可以移动。
from __future__ import absolute_import
from .modx import does_something