![](/img/trans.png)
[英]Python script using PIL works in IDE doesn't when run by cmd and gives 'PIL' has no attribute 'Image'
[英]Python PIL has no attribute 'Image'
我正在使用python2.6,今天早上遇到了问题。 它说“模块”没有属性“图像”。 这是我的输入。 为什么我第一次不能使用 PIL.Image?
>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
PIL 的__init__.py
只是一个常见的空存根。 它本身不会神奇地导入任何东西。
当您from PIL import Image
执行时,它会在 PIL 包中查找并找到文件 Image.py 并导入该文件。 当您执行PIL.Image
时,您实际上是在 PIL 模块上进行属性查找(除非您明确导入内容,否则这只是一个空存根)。
实际上,导入模块通常不会导入子模块。 os.path
是一个著名的例外,因为 os 模块很神奇。
更多信息:
图像模块
如果您像我一样发现接受的答案有点令人困惑,因为您可以发誓您已经能够使用
import PIL
PIL.Image
有时,一个潜在的原因是,如果您的 Python 会话中的任何其他代码已经from PIL import Image
或import PIL.Image
,即使它在完全不同的范围内,您也可以访问PIL.Image
。
特别是, matplotlib
在导入时会这样做。 所以如果你跑
import matplotlib
import PIL
PIL.Image
它有效。 谢谢,蟒蛇。
不要相信任何人。 不要相信 Python。 使用import PIL.Image
。
你可以做:
try:
import Image
except ImportError:
from PIL import Image
最好用枕头代替 PIL。
而不是from PIL import Image
或import PIL
尝试
`PIL.Image`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.