python 自定义模块 ModuleNotFoundError
问题描述
现有如下文件结构:
1 | - simulator |
- 在
simulator.py中,使用from utils import utilities。 - 在
utility.py中,使用import constant as const。
以 simulator 为工作目录,在命令行运行 python simulator.py,会出现报错:
1 | Traceback (most recent call last): |
解决方法
出现问题的原因是,python 解释器在运行 utility.py 文件时,找不到 constant.py 文件。因为运行代码的工作目录为 simulator 文件夹,因此解释器搜索的目录中不会包含 utils 文件夹。
此时只需要在 simulator.py 代码前加上
1 | import sys |
将 utils 文件夹加入搜索目录即可。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Zhuxz's Blog!
评论




