来自子目录的 ImportError
ImportError from subdirectory
当 sub-directory 中的模块从同一目录中的另一个模块导入时出现导入错误。我认为错误是由于计算机权限引起的,但是我无法诊断它。文件夹结构如下
/test_import
test.py
/imports
__init__.py
aa.py
bb.py
含bb.py含
from aa import myfun
aa.py包含
def myfun():
print("hello")
和test.py包含
if __name__ == "__main__":
from imports import bb
bb.myfun()
在我的电脑上 运行我得到了预期的结果运行
C:\Users\mgilbert\test_import>python test.py
hello
但是在另一个盒子上我收到以下错误
无论出于何种原因,当我尝试 运行 >python test.py 时,这会导致导入错误,但是如果我开始 ipython 并进行相关导入,则效果很好?
您正在使用隐式相对导入。这些 no longer exist in Python 3 因为坦率地说,它们带来的麻烦多于它们的价值。
将 bb.py
中的导入更改为:
from imports.aa import myfun
当 sub-directory 中的模块从同一目录中的另一个模块导入时出现导入错误。我认为错误是由于计算机权限引起的,但是我无法诊断它。文件夹结构如下
/test_import
test.py
/imports
__init__.py
aa.py
bb.py
含bb.py含
from aa import myfun
aa.py包含
def myfun():
print("hello")
和test.py包含
if __name__ == "__main__":
from imports import bb
bb.myfun()
在我的电脑上 运行我得到了预期的结果运行
C:\Users\mgilbert\test_import>python test.py
hello
但是在另一个盒子上我收到以下错误
无论出于何种原因,当我尝试 运行 >python test.py 时,这会导致导入错误,但是如果我开始 ipython 并进行相关导入,则效果很好?
您正在使用隐式相对导入。这些 no longer exist in Python 3 因为坦率地说,它们带来的麻烦多于它们的价值。
将 bb.py
中的导入更改为:
from imports.aa import myfun