I get "ModuleNotFoundError: No module named "
A little background:
1) My venv is using python 3.6.9
2) Already tried adding the folders to PYTHONPATH via sys.path.append
3) Heirarchy, or the relevant part:
/project folder
|--folder A
|--__init__.py
|--a.py
|--folder B
|--__init__.py
|--b.py
|--init.py
I am trying to import from a.py to b.py Tried it in various ways-
1) import b
2) from b import x
Would really appreciate some help, been on this for some time now.
Why?Because you run your script differently. When you run it with PyCharm then PyCharm adds project directory and all the sourse directories to
sys.path. That's whyimport A.aworks. However when you run your script with console command then only file location is added tosys.path. Just printsys.pathto see what it contains.To solve the issue you may use various approaches.
Easiest way is to use
PYTHONPATH. For example, on Windows you can run commandset PYTHONPATH=[project_folder];%PYTHONPATH%thenimport A.aworks. Or you can run slightly different versionset PYTHONPATH=[project_folder/A];%PYTHONPATH%thenimport aworks. Basically this command adds directory tosys.path.Alternative solution is to have
mainfunction inb.pyand somelaunching_script.pyinproject_folder. Instead of runningb.pyyou run yourlaunching_script.py. Thus you always have project directory insys.path. So absolute imports starting with project directory (likeimport A.a) will work in both PyCharm and console.Another approach is some ugly code like the following one:
Also you may use relative imports. A little harder, less readable and error-prone way demanding some work on the project structure.