AttributeError:__ exit__在python 2.7上缓冲下载的图像时

时间:2016-07-30 22:50:30

标签: python image python-2.7 python-imaging-library buffering

我正在尝试使用python脚本自动执行验证码文件识别。 然而,经过几天的努力,我的功能似乎远非理想的结果。

此外,我所获得的追溯信息不足以帮助我进一步调查。

这是我的功能:

def getmsg():
    solved = ''
    probe_request = []
    try:
        probe_request = api.messages.get(offset = 0, count = 2)
    except apierror, e:
        if e.code is 14:
            key = e.captcha_sid
            imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read())
            img = Image.open(imagefile)
            imagebuf = img.load()
            with imagebuf as captcha_file:
                captcha = cptapi.solve(captcha_file)
    finally:
        while solved is None:
            solved = captcha.try_get_result()
            tm.sleep(1.500)
        print probe_request

这是追溯:

Traceback (most recent call last):
  File "myscript.py", line 158, in <module>
    getmsg()
  File "myscript.py", line 147, in getmsg
    with imagebuf as captcha_file:
AttributeError: __exit__

有人可以澄清我到底做错了什么吗?

如果没有缓冲,我的图像处理也没有成功:

key = e.captcha_sid
response = requests.get(e.captcha_img)
img = Image.open(StringIO.StringIO(response.content))
with img as captcha_file:
    captcha = cptapi.solve(captcha_file)

导致:

    captcha = cptapi.solve(captcha_file)
  File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 62, in proxy
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 75, in proxy
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 147, in solve
    raw_data = file.read()
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 632, in __getattr__
    raise AttributeError(name)
AttributeError: read

1 个答案:

答案 0 :(得分:0)

imagebuf不是context manager。您无法在with语句中使用它,该语句首先存储contextmanager.__exit__ method来测试上下文管理器。也没有必要关闭它。

cptapi.solve需要一个类似文件的对象;来自solve() docstring

  

将验证码排队以进行解决。 file可以是路径或文件对象。

传递Image对象没有意义,只需传入StringIO实例:

imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read())
captcha = cptapi.solve(imagefile)

同样,此处无需关闭该对象,您也不需要使用with