1

I think I'm missing something obvious here. I cloned this repo, and now have this directory structure on my computer:

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

When I try to run python baby_cry_detection/pc_main/train_set.py, I get a 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'

However, if I type python and enter the interactive shell and then type the command

from baby_cry_detection.pc_methods import Reader

it imports just fine with no error. I'm completely baffled. I'm using a virtualenv and both instances are using the same python installation, and I haven't changed directories at all.

Chase Roberts
  • 9,082
  • 13
  • 73
  • 131

1 Answers1

2

I think sys.path could be the reason that the module is not found when python command is executed. Here is how we can check if that is indeed the case:

In the train_set.py file, add import sys; print(sys.path). Looking at the error, the path may contain /path/to/baby_cry_detection/baby_cry_detection/pc_main. If that is the case, then we have found the issue which is that baby_cry_detection.pc_methods will not be found in the directory that sys.path is looking into. We'll need to append the parent baby_cry_detection directory to sys.path or use relative imports. See this answer.

The reason that python prompt successfully imports the module could be because the prompt is started in the correct parent directory. Try changing the directory to baby_cry_detection/pc_main/ and try importing the module.

S.Au.Ra.B.H
  • 457
  • 5
  • 9
  • I think you're right. The problem now is that when I try to do a relative import I get `ImportError: attempted relative import with no known parent package` even though I have init files up and down the directory structure. But that's another question for another day I guess. – Chase Roberts Feb 26 '21 at 01:13