/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
/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
这个问题的导致原因是:如果直接使用运行python ./programs/my_python_program.py的话,编译器会在脚本所在的目录查找包,那么就看不到当前目录外边的包,因此就会有导入错误
有三种解决方法:
sys.path.append(os.path.join(os.path.dirname(file), '..'))
import programs.my_python_program programs.my_python_program.main()
python -m programs.my_python_program