我想到了。非常令人沮丧,尤其是来自python2。
.
无论它是相对的还是绝对的,您都必须将 a 添加到模块中。
我按如下方式创建了目录设置。
/main.py
--/lib
--/__init__.py
--/mody.py
--/modx.py
修改文件
def does_something():
return "I gave you this string."
模块.py
from modx import does_something
def loaded():
string = does_something()
print(string)
主文件
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
我不得不修改 mod.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