Question
Asked By – bodacydo
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.
Now we will see solution for issue: How to fix “ImportError: No module named …” error in Python?
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
.
This question is answered By – Ignacio Vazquez-Abrams
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0