Issue
I am trying to import a module from a different directory:
from preprocess.utils import get_image
But this is the error that I get:
ModuleNotFoundError: No module named 'preprocess'
I tried editing the .batch_profile
, and setting the PYTHONPATH as follows but it still doesn't fix the error:
export PYTHONPATH="/Users/username/documents/project_directory/"
How can I fix this error?
Solution
Python automatically adds the project directory to the module load path (sys.path
). However, depending on how you run the file, the which directory is picked is different. When you run python preprocess/filename.py
, the directory added to the load path is the directory that the script is in: preprocess
. If you execute the program as a module, run it as python -m preprocess.filename
, the current working directory is the one added to the load path, and your code should work.
If you want to execute your script using python preprocess/filename.py
syntax, the easiest fix is to move filename.py
to the project root directory, or to make a wrapper script that will reside in the root and import preprocess.filename
.
export PYTHONPATH="/Users/username/documents/project_directory/"
should also work, but it is not really great; what if you start working on a different project? That aside, putting it into .bash_profile
should work though, as long as you have made sure it was actually executed. On OSX, it is executed automatically when you open a new Terminal. On most other flavours of UN*X, it is executed only when you log in. If you have made changes to .bash_profile
, they won't take effect until you trigger the above (new Terminal or re-login), or you explicitly execute them using source ~/.bash_profile
.
You can check which directory was auto-added to the load path by executing the following as the first line in your preprocess/filename.py
:
import sys; print(sys.path)
Answered By - Amadan Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.