0

I am working on a little project and I don't really understand why I get the ModuleNotFoundError. I have the following directory structure:

project structure

My code imports the following:

import asyncio

import socketio

from core.databases.mongo_handler import create_donation, get_streamer
from core.models.donations import Donation

When I try to execute the code from the command line I get the following error:

(venv) user@host % python standalone/sockets.py 
Traceback (most recent call last):
  File "/Users/user/Project/standalone/sockets.py", line 5, in <module>
    from core.databases.mongo_handler import create_donation, get_streamer
ModuleNotFoundError: No module named 'core'

I do not understand why I get that error.

Sone clarifications:

  • I do not have __init__.py files in the different directories but it doesn't change anything with them, I have tried it.
  • I want to run the code from the root of the project which is why I run it with python standalone/sockets.py
tcastron
  • 11
  • 5
  • Try using `.core` instead of `core` – GGberry Apr 07 '22 at 16:21
  • What about an `__init__.py` file in the directories? Additionally, the `sys.path` must be set in a way such that the importing modules can ‘see’ the modules being imported. In other words, the first element in `sys.path` can (generally) be the project root, then imports are relative to this path. – S3DEV Apr 07 '22 at 16:21
  • 1
    Have a browse through [this question](https://stackoverflow.com/q/14132789/6340496). – S3DEV Apr 07 '22 at 16:25
  • The file you are trying to import is in a directory that is in the parent directory. I am pretty sure that you will have to place your `sockets.py` file in the parent folder too in order to import from the `core` folder. – Omer Apr 07 '22 at 16:52
  • @GGberry your solution did not work :/ thanks for the help tho – tcastron Apr 07 '22 at 17:03
  • @S3DEV thanks for the link, I will read this now. I tried with the `__init__.py` file but it didn't work. – tcastron Apr 07 '22 at 17:04
  • @Omer it does work when I put the file in the parent directory but is there any way I could avoid this ? – tcastron Apr 07 '22 at 17:05

1 Answers1

1

[SOLVED]

Thanks to S3DEV and his link I found the answer.

Due to the fact that I was running my file as a script and not a module, I cannot import modules in a relative way. To solve this issue and keep my directory structure I need to run the script as follows:

python -m standalone.sockets

Now I ask python to consider this as a module and everything works perfectly fine. Hope this helps other people too !

tcastron
  • 11
  • 5