Importerror: No Module Named … Error In Python - Set Pythonpath Still Not Working
Solution 1:
I have a writeup on this but I'll copy the relevant text inline.
You have two problems:
- You need to export
PYTHONPATH
(export PYTHONPATH=/full/path/to/src
) - You should run with
python -m module.path
instead ofpython path/to/file.py
The core problem is python path/to/file.py
puts path/to
on the beginning of the PYTHONPATH
(sys.path
)
This causes imports to start from (in your case) src/ml
instead of the expected src
.
By using -m
, you avoid this path munging and it will correctly keep src
as the beginning of your sys.path
.
When I test this in PyCharm, it works if set python/src to become source root, regardless what working directory is. But I cannot figure out how to set this properly when I run this from command line.
You can do this by cd
ing into the src
directory
Solution 2:
You should not put executable scripts into a library structure.
Only library modules should go into the package structure. Executables should stay outside it. This is important for installation and day-to-day use. Once you have installed your package (using distutils for example) using it would be complicated, if you leave the executable in the library. You would have to give the complete installation path into the python library (and don't forget about -m
!) every time or create shortcuts or other workarounds.
Seperate executables and library. Executables are installed to something like usr/local/bin
and are callable without path, -m
or other problems, and your library is installed into the python library.
Post a Comment for "Importerror: No Module Named … Error In Python - Set Pythonpath Still Not Working"