从命令行运行时出现Python3 ModuleNotFoundError,但如果我进入shell,则会起作用

2024-04-25 14:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我错过了一些明显的东西。我克隆了this repo,现在我的计算机上有了这个目录结构:

screenshot of the directory structure. Main file being ~/baby_cry_detection/baby_cry_Detection/pc_main/train_model.py

当我试图运行python baby_cry_detection/pc_main/train_set.py时,我得到一个ModuleNotFoundError

Traceback (most recent call last):
  File "baby_cry_detection/pc_main/train_set.py", line 10, in <module>
    from baby_cry_detection.pc_methods import Reader
ModuleNotFoundError: No module named 'baby_cry_detection'

但是,如果我键入python并输入交互式shell,然后键入命令

from baby_cry_detection.pc_methods import Reader

它导入得很好,没有错误。我完全不知所措。我使用的是virtualenv,两个实例都使用相同的python安装,我根本没有更改目录


Tags: frompyimport目录maintrainreaderbaby
1条回答
网友
1楼 · 发布于 2024-04-25 14:28:24

我认为^{}可能是执行python命令时找不到模块的原因。以下是我们如何检查情况是否属实的方法:

train_set.py文件中,添加import sys; print(sys.path)。查看错误,路径可能包含/path/to/baby_cry_detection/baby_cry_detection/pc_main。如果是这样的话,那么我们发现了一个问题,即baby_cry_detection.pc_methods将不会在sys.path正在查找的目录中找到。我们需要将父目录baby_cry_detection附加到sys.path或使用相对导入。见this答案

python提示符成功导入模块的原因可能是提示符在正确的父目录中启动。尝试将目录更改为baby_cry_detection/pc_main/,然后尝试导入模块

相关问题 更多 >