我想到了。非常令人沮丧,尤其是来自python2。
.
无论模块是相对的还是绝对的,都必须向模块添加a 。
我创建目录设置如下。
/main.py
--/lib
--/__init__.py
--/mody.py
--/modx.py
修改器
def does_something():
return "I gave you this string."
么
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
我不得不修改mody.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