How to fix "ImportError: No module named ..." error in Python?


What is the correct way to fix this ImportError error?

I have the following directory structure:


And I am in the directory


Now if I type

python ./programs/

I instantly get

ImportError: No module named foo.tasks

The ./programs/ contains the following line:

from foo.tasks import my_function

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

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

>>> from foo.tasks import my_function

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

7/9/2015 8:36:23 PM

Accepted Answer

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.

2/24/2010 12:47:46 PM

Do you have a file called 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow