tags:

views:

156

answers:

3

What is the correct way to fix this ImportError error?

I have the following directory structure:

/home/bodacydo
/home/bodacydo/work
/home/bodacydo/work/project
/home/bodacydo/work/project/programs
/home/bodacydo/work/project/foo

And I am in the directory

/home/bodacydo/work/project

Now if I type

python ./programs/my_python_program.py

I instantly get

ImportError: No module named foo.tasks

The ./programs/my_python_program.py contains the following line:

from foo.tasks import my_function

I can't understand why python won't find ./foo/tasks.py - it's there.

If I do it from the Python shell, then it works:

python
>>> from foo.tasks import my_function

It only doesn't work if I call it via python ./programs/my_python_program.py script.

Help me fix it!

Thanks, Boda Cydo.

+2  A: 

Python does not add the current directory to sys.path, but rather the directory that the script is in. Add /home/bodacydo/work/project to either sys.path or $PYTHONPATH.

Ignacio Vazquez-Abrams
Added it to $PYTHONPATH and it worked. Thank you Ignacio!
bodacydo
+1  A: 

Do you have a file called __init__.py in the foo directory? If not then python won't recognise foo as a python package.

See the section on packages in the python tutorial for more information.

Dave Kirby
Thanks and yes, I had `__init__.py`. The problem this time was with `$PYTHONPATH`. Ignacio's solution worked.
bodacydo
A: 

In my mind I have to consider that the foo folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages folder within a python installation. I might want to consider adding a foo.pth file there.

I know its a library since:

the ./programs/my_python_program.py contains the following line:

from foo.tasks import my_function

So it doesn't matter that ./programs is a sibling folder to ./foo its the fact that my_python_program.py is run as a script like this:

python ./programs/my_python_program.py
quamrana