在Python中关闭asyncio事件循环会导致异常结束

时间:2014-04-25 03:09:37

标签: python-3.x python-asyncio aiohttp

对于在Windows上使用Python 3.4中的asyncio和aiohttp的https请求,我需要使用2个事件循环。 ProactorEventLoop用于运行shell命令,以及HTTPS请求的默认事件循环。遗憾的是,ProactorEventLoop不适用于HTTPS命令。

下面的代码显示了当我使用新创建的默认事件循环并尝试在Windows结束时关闭它时会发生什么。如果我在最后调用loop.close,我会在最后得到例外情况,如下所示:

> Traceback (most recent call last):
>  File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 56, in __del__
>    self.close()
>  File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 97, in close
>    transport.close()
>  File "C:\Python34\Lib\asyncio\selector_events.py", line 375, in close
>    self._loop.remove_reader(self._sock_fd)
>  File "C:\Python34\Lib\asyncio\selector_events.py", line 155, in remove_reader
>    key = self._selector.get_key(fd)
> AttributeError: 'NoneType' object has no attribute 'get_key'

评论它会删除异常,我不知道为什么。唯一的

import asyncio
import aiohttp

@asyncio.coroutine
def get_body(url):
    response = yield from aiohttp.request('GET', url)
    return (yield from response.read_and_close())

#loop = asyncio.ProactorEventLoop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

f = asyncio.async( get_body('https://www.google.com') )
try:
    loop.run_until_complete(f)
except Exception as e:
    print(e)

if f.result():
    print(f.result())

loop.close()

谢谢, greenaj

3 个答案:

答案 0 :(得分:2)

更新:看起来问题已在github版本(0.7.2)中修复。它不会产生错误。作为@danj.py said,它由"Get rid of __del__ in connector" commit确定。


它不是ProactorEventLoop或Windows特定的。我可以使用默认的事件循环在Ubuntu上重现错误:

#!/usr/bin/env python3
import asyncio
import aiohttp # $ pip install aiohttp

@asyncio.coroutine
def get_body(url):
    response = yield from aiohttp.request('GET', url)
    return (yield from response.read_and_close())

loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()

它可能是aiohttp中的一个错误,因为用法似乎是正确的。

如果请求是在没有aiohttp的情况下发出的,则没有错误:

#!/usr/bin/env python3
import asyncio
from contextlib import closing
from urllib.parse import urlsplit

@asyncio.coroutine
def get_body(url):
    # parse url
    url = urlsplit(url)
    path = '/' * (not url.path) + url.path + '?' * bool(url.query) + url.query
    # open connection
    reader, writer = yield from asyncio.open_connection(
        host=url.hostname,
        port=url.port or (443 if url.scheme == 'https' else 80),
        ssl=(url.scheme == 'https'))
    with closing(writer):
        # send request
        writer.write(b'GET ' + path.encode('ascii') + b' HTTP/1.1\r\n'
                     b'Host: ' + url.netloc.encode('ascii') + b'\r\n'
                     b'Connection: close\r\n\r\n')
        # read headers
        while True:
            line = yield from reader.readline()
            line = line.rstrip(b'\n\r')
            print(line.decode('latin-1'))
            if not line:
                break
        # read body
        body = yield from reader.read()
    return body

loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()

注意:示例并不完全等效,例如,后者不遵循重定向。

答案 1 :(得分:2)

J.F。塞巴斯蒂安说这是aiohttp的错误。

看起来此问题已通过以下提交解决。

https://github.com/KeepSafe/aiohttp/commit/a229110539e93c21ae0198f6f883ae3e40ea866b#diff-7f25afde79f309e2f8722c26cf1f10ad

在撰写本文时,似乎没有进入pypi。

答案 2 :(得分:1)

实际上它是Python 3.4本身的一个(固定的)错误:http://bugs.python.org/issue21435

作为临时解决方案(为了支持Python 3.3),我提出了拉取请求https://github.com/KeepSafe/aiohttp/pull/48

但是,再说一遍,问题的根源是Python 3.4.0中的垃圾收集器(由即将发布的Python 3.4.1错误修正版本修复)。

相关问题