[英]Python3 ModuleNotFoundError when running from command line but works if I enter the shell
我想我在这里遗漏了一些明显的东西。 我克隆了这个 repo ,现在我的电脑上有这个目录结构:
当我尝试运行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 安装,而且我根本没有更改目录。
我认为sys.path
可能是执行python
命令时找不到模块的原因。 以下是我们如何检查是否确实如此:
在train_set.py
文件中,添加import sys; print(sys.path)
import sys; print(sys.path)
。 查看错误,路径可能包含/path/to/baby_cry_detection/baby_cry_detection/pc_main
。 如果是这种情况,那么我们发现了在sys.path
正在查找的目录中找不到baby_cry_detection.pc_methods
的问题。 我们需要将 append 父baby_cry_detection
目录添加到sys.path
或使用相对导入。 看到这个答案。
python 提示成功导入模块的原因可能是提示是在正确的父目录中启动的。 尝试将目录更改为baby_cry_detection/pc_main/
并尝试导入模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.