I tried to read how import
works and use what is suggested, but I still have questions:
If I cd
to project
folder and run python ./test/test1.py
I get ModuleNotFoundError: No module named 'lib'
.
- If I add
print(os.getcwd())
it does print the current directory which isproject
. So, why it cannot findlib
folder? - If I
cd
toproject/test
, addimport sys sys.path.append('..')
to the beginning oftest1.py
and then runpython test1.py
it works. But, why I cannot run it from one level above? - I also tried to add
__init__.py
tolib
andtest
folders, but I get same error. - If I try changing to relative path
from .lib.lib1 ...
and run thetest.py
fromproject
folder I getImportError: attempted relative import with no known parent package
error
What am I doing wrong?
test1.py
from lib.lib1 import MyClass
Project structure
project
lib
lib1.py
lib2.py
test
test1.py # from lib.lib1 import MyClass
main.py