Sycan
Sycan

Reputation: 47

How to set PYTHONPATH to a project directory?

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?

Upvotes: 1

Views: 6037

Answers (2)

Amadan
Amadan

Reputation: 198526

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)

Upvotes: 1

Michael Sohnen
Michael Sohnen

Reputation: 980

I use windows and I also could not get changing "PYTHONPATH" to work predictably.

In your case, you can do something like

import sys
sys.path.insert(0,"path_that_you_want")

Depending on your version of python, you may need to put an __init__.py file in that directory and all subdirectories. Blank __init__.py files are fine.

Please note that for syntax highlighting in some code editors you will need to include that path in the code editor config. (e.g. settings.json in VSCode)

Upvotes: 0

Related Questions