Python version: 3.8.5
File structure
MainDir
|
| Utils --|
| | module1.py
| | module2.py
|
| Tests --|
| test.py
module1.py imports module2.py
test.py imports module1.py
When I run python Tests/test.py I get the following error:
Traceback (most recent call last):
File "test.py", line 5, in <module>
import Utils.module1
File "<abspath>/MainDir/Utils/module1.py", line 16, in <module>
import module2
ModuleNotFoundError: No module named 'module2'
I've tried the following:
2.)
$export PYTHONPATH="$PWD"
3.) I've tried putting the test.py file at the same level as the Utils directory.
4.)
import sys
sys.path.append("../MainDir")
And several variations thereof.
They all failed.
The only thing that worked was just putting test.py in the Utils directory and running it from there. But I know there has to be a way to get it to work when it's in its own directory.
What am I missing?
UPDATE
The selected answer worked when trying to run test.py, but it broke when trying to run module1.py.
After some more research, running it with the -m flag and package syntax worked; in my case:
python -m Utils.module1
Hope this helps anyone else who runs into this problem.
__init__.pyfile to theUtilsdirectory so that python recognizes it as a package... check the doc here