1

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?

6
  • I'd suggest removing the bash tag unless you can validate that the bash code really isn't doing what it should. If you run env | grep PYTHONPATH, is the value you expect shown? If it is, not a bash problem. Commented May 17, 2016 at 2:51
  • env | grep PYTHONPATH shows path, went ahead and removed bash tag....thank you :) Commented May 17, 2016 at 2:54
  • What exactly is the import line in app.py that isn't working? Commented May 17, 2016 at 2:56
  • from src import testfunction Commented May 17, 2016 at 2:57
  • 1
    from src? then you need project to be in your PYTHONPATH, not project/src, and testfunction needs to be defined in src/__init__.py. Commented May 17, 2016 at 3:02

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

You are right....thanks! The module does seem to get imported and am able to import them successfully. But, my editor(s) still do not seem to autocomplete the functions. I tried with 2 different ones (Atom and Spyder) and both fail.
I finally got it to work with Atom! There was an additional setting where we could specify the particular package (/home/username/Desktop/project) that we would want and autocomplete works! Not sure why it does not automatically pick it up from PYTHONPATH. Thanks again, this answer solves my issue. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.