我有这个文件夹结构:
--test
first.py
--numpad
second.py
third.py
在first.py中,我有以下代码行:
from numpad import second
在second.py文件中,我有这个:
import third
但是当我运行时在测试文件夹中
python first.py
我收到此错误消息:
ModuleNotFoundError:没有名为“第三”的模块
注意:我也曾尝试添加__init__.py
到我的numpad文件夹中,但没有成功
由于python解释器是在中启动test
的,因此它是查找导入的地方。如果您对详细信息感兴趣,可以通过docs了解python搜索导入行为。
为了解决您的问题,有很多解决方法,最好的方法取决于您计划如何使用代码。如果您打算编写一个库,则打包它可能很有意义,这将使您能够访问可以使用的全局名称空间。
但是,如果您只是希望它现在就可以工作,并且只有从同一位置(即您的test
文件夹)运行解释器,则将文件定义third
为本地文件应该可以:
第二个
from . import third
第三
print('third here, not an import error')
这对我有用:
~/test$ tree .
.
├── first.py
└── numpad
├── second.py
└── third.py
~/test$ python3.6 first.py
third here, not an import error
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句