PIL和导入语句有什么情况
我在Django中发现了这段代码:
# Try to import PIL in either of the two ways it can end up installed.
try:
from PIL import ImageFile as PILImageFile
except ImportError:
import ImageFile as PILImageFile
直到最近,我一直觉得这没什么大不了的。不过,我在Windows的虚拟环境中安装了PIL,突然间
from PIL import Image
就不再工作了,我必须使用
import Image
所以,现在我想搞明白这是为什么,发生了什么。
最开始我是在Windows上用Windows安装程序安装的PIL。但是我需要支持读取Group4传真,所以我做了一些修改,然后在Windows的虚拟环境中成功构建并安装了PIL(在Linux上这很简单,但在Windows上就麻烦了)。但是现在我必须使用第二种导入方式,尽管用pip freeze
查看时显示PIL==1.1.7
已经安装了。
为什么第一种导入方式不工作,尽管PIL看起来已经安装了,而第二种导入方式却可以使用(而且PIL的代码也在正常运行),但在PIL下却没有显示出来呢?
1 个回答
4
编辑: 根据@cgohlke对我回答的评论,在PIL1.2中会有所变化:
对从标准命名空间导入的支持[已经取消];PIL现在只存在于PIL命名空间中。
我觉得Django的评论很清楚:
# Try to import PIL in either of the two ways it can end up installed.
PIL可以作为一个整体包安装,这样你就可以访问其中的模块:
from PIL import ImageFile as PILImageFile
或者每个模块也可以单独安装:
import ImageFile as PILImageFile
所以PIL是安装了,只不过它被拆分成了不同的模块。
这也是在使用virtualenv或buildout安装PIL时的问题,@Ignacio在评论中提到,PIL教程实际上是期望以这种方式安装的,第一段代码是:
>>> import Image
而不是from PIL import Image
。
我同意这确实让人困惑,但我想这是因为这个包比较大,他们可能觉得不需要处理额外的层级会更简单。
这似乎也是在Python - 使用easy_install安装的包未被检测到(PIL 1.1.7)中的问题,虽然只有最后一个回答者搞清楚了,其他人都不知道发生了什么。