我已经搜索了一段时间来找到这个问题的解决方案但是已经干了.我希望我能在这里找到一些帮助.正如标题所示,
python无法识别已在我的PYTHONPATH中设置的模块.
我目前正在开发一个具有以下整体结构的项目:
base
├── util
│ └── logging_utility.py
└── project
└── app
├── config.py
└── runner.py
这是通过名为venv_1的虚拟环境在python 3.5中执行的.我用的是运行El Capitan的Mac.
我的runner.py脚本使用以下import语句调用logging_utility:
来自util.logging_utility导入方法.
执行时,我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'util.logging_utility'
我从目录的基础级别在终端中运行它.我正在使用以下命令来调用脚本:
PYTHONPATH=$HOME/base VIRTUAL_ENV=$HOME/.virtualenvs/venv_1 PATH=$VIRTUAL_ENV/bin:$PATH $HOME/.virtualenvs/venv_1/bin/python -- project/app/runner.py
现在,我试图通过打印出我的env和sys.path来调试它.在这两种情况下,基本目录都会显示在路径中.那么为什么我收到这个错误呢?
我也尝试将import语句更新为base.util.logging_utility导入方法,它给出了以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'base'
知道为什么会这样,以及我如何纠正这个问题?
谢谢!
UPDATE
感谢Billy和Moinuddin Quadri,他们的建议解决了这个问题.出于某种原因,我仍然需要添加__init__.py文件.即使python 3.3支持隐式导入,看起来仍然需要它.这解决了这个问题.
最佳答案 您可能没有在PYTHONPATH中打包的路径.为了添加它,请执行以下操作:
import sys
sys.path.append('/absolute/path/to/base')
从Python 3.3起,您不需要__init__.py.
对于旧版本,另一个可能的原因是缺少__init__.py.如果目录中没有__init__.py文件,则无法导入该目录的文件.
正如Packages Document中提到的:
The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case,__init__.py
can just be an empty file, but it can also execute initialization code for the package or set the__all__
variable, described later.