1

I have examined many questions that have been asked before but I couldn't find a solution to my problem.

I'm running python3 folder1/script1.py command on the terminal in the root directory but I get the error ModuleNotFoundError: No module named 'folder2'. I added __ init __.py to the folders but still couldn't find a solution.

My project directory is like this:

└── root
    ├── folder1
    │   ├── script1.py
    │   
    └── folder2
        ├── module1.py

module1.py:

def say_hello():
    print('hello')

scipt1.py:

from folder2 import module1

module1.say_hello()

enter image description here

Uğur Eren
  • 163
  • 3
  • 11

2 Answers2

1

Generally, python modules need to be installed for python to find them. One side rule is that python will look in a script's path to see if the module is there. Move script1.py down a level, make sure you have an __init__.py and it will work.

└── root
    ├── script1.py
    │   
    └── folder2
        ├── __init__.py
        ├── module1.py

You could also have script1.py insert its grandparent directory into sys.path. But really the best way to solve the problem is to make the package installable by adding a setup.py. An extremely primitive version is

import setuptools

setuptools.setup(
    name="Foobar",
    packages=setuptools.find_packages(),
    scripts=["folder1/script1.py"]
)

and your directory can be

└── root
    ├── setup.py
    ├── folder1
    │   ├── script1.py
    │   
    └── folder2
        ├── __init__.py
        ├── module1.py

Now you can do python setup.py develop to run your script from your development directory. Or python setup.py install (frequently in a venv you created) to make it a standard install.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

Right usage for init with double underscores;

__init__ 

I added _ init _.py to the folders but still couldn't find a solution.

You write init with just one.

Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85