I’m using Python 3.7.1 on macOS Mojave Version 10.14.1
This is my directory structure:
man/
Mans/
man1.py
MansTest/
SoftLib/
Soft/
SoftWork/
manModules.py
Unittests/
man1test.py
man1.py
contains the following import statement, which I do not want to change:
from Soft.SoftWork.manModules import *
man1test.py
contains the following import statements:
from ...MansTest.SoftLib import Soft
from ...Mans import man1
I need the second import in man1test.py
because man1test.py
needs access to a function in man1.py
.
My rationale behind the first import (Soft) was to facilitate the aforementioned import statement in man1.py
.
Contrary to my expectation, however, the import statement in man1.py
gives rise to:
ModuleNotFoundError: No module named 'Soft'
when I run
python3 -m man.MansTest.Unittests.man1test
from a directory above man/.
Is there any way to resolve this error without changing the import statement in man1.py
and without adding anything to sys.path?
Edit: python3 -m man.ManTest.Unittests.man1test
from the original version of the question changed to python3 -m man.MansTest.Unittests.man1test
Kenil Vasani
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
You need to set it up to something like this:
SECOND, for the “
ModuleNotFoundError: No module named 'Soft'
” error caused byfrom ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py tosys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don’t want to modifysys.path
directly, you can also modifyPYTHONPATH
:THIRD, for
from ...MansTest.SoftLib import Soft
which you said “was to facilitate the aforementioned import statement in man1.py“, that’s now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.With that said, here’s how I got it to work.
man1.py:
man1test.py
manModules.py
Terminal output:
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of “bridge” between man1.py and man1test.py? The way your files are setup right now, I don’t think it’s going to work as you expect it to be. Also, it’s a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).