lordlabakdas lordlabakdas - 2 years ago 83
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:

- src/
- src_a.py
- __init__.py
- bin/
- __init__.py
- app.py

I added
as given below:

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

in my
followed by a
$ source ~/.bashrc

I am still not able to get the module to be recognized in
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download