lordlabakdas lordlabakdas - 6 months ago 15
Python Question

importing Python module using PYTHONPATH in ~/.bashrc not working

I have been trying to do a simple import of a Python module and have been running into problems with this simple operation.

I have a directory structure as below:

/home/username/Desktop/project
- src/
- src_a.py
- __init__.py
- bin/
- __init__.py
- app.py


I added
/home/username/Desktop/project/src
to
PYTHONPATH
as given below:

export PYTHONPATH="${PYTHONPATH}:/home/username/Desktop/project/src"


in my
~/.bashrc
followed by a
$ source ~/.bashrc
.

I am still not able to get the module to be recognized in
app.py
nor anywhere else. My editor also does not seem to recognize (autocomplete) the module. I search through multiple related questions and they point to the same procedure. Am I missing something?

Answer

You have created packages named src and bin. If you want to import something from a package, you need to set your PYTHONPATH to the directory containing the package's directory, in this case:

export PYTHONPATH=${PYTHONPATH}:/home/username/Desktop/project

Now you should be able to import like this:

from src import src_a

Also, since bin is a package in the same directory you can import objects from it:

from bin import app
Comments