Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module Not Found Error - Importing from sibling directory

So I have tried many solutions found on stack overflow but am still having issues.

Below is my project structure.

project
    | tool1
       | - application.py
    | resources
       | - tools
          | - dao.py

Within application.py I have the following import statement:

from resources.tools.dao import DAO

This works fine in PyCharm, but when I try to run it from the command line from the project directory (python tool1/application.py), I get:

ModuleNotFoundError: No module named 'resources'

I get the same error if I move into 'tool1' folder and run: python application.py

I have tried adding .. before the imports, setting different folders as my source root folder through PyCharm, and adding blank __init__.py files to the resources directory.

Why is PyCharm able to find 'resources' but the command line is not? How can I change this so that my solution works from either location?

If it helps, I am using Python 3.7 and Windows. I am open to restructuring the project directory, but there are going to be multiple tools/applications that will all use dao.py and the other tools in the resources directory, so resources should be at least as high level as the other projects.

Thank you in advance.

like image 640
db702 Avatar asked Nov 07 '25 22:11

db702


1 Answers

Run the script using the -m argument. i.e.

python -m project.tool1.application

This makes the script run with the project package in the namespace. (You may need to add an __init__.py file to project to make it a package)

like image 95
ryansept Avatar answered Nov 09 '25 13:11

ryansept