aiohttp - 异常忽略的消息

时间:2015-04-07 22:52:10

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

我正在运行以下代码,通过aiohttp发出5个请求:

import aiohttp
import asyncio

def fetch_page(url, idx):
    try:
        url = 'http://google.com'
        response = yield from aiohttp.request('GET', url)

        print(response.status)
    except Exception as e:
        print(e)

def main():
    try:
        url = 'http://google.com'
        urls = [url] * 5

        coros = []
        for idx, url in enumerate(urls):
            coros.append(asyncio.Task(fetch_page(url, idx)))

        yield from asyncio.gather(*coros)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    try:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
    except Exception as e:
        print(e)

输出:

200
200
200
200
200
Exception ignored in: Exception ignored in: Exception ignored in: Exception ignored in: Exception ignored in:

注意:没有关于异常的内容/位置的其他信息。

导致这种情况的原因是什么,有没有调试它的提示?

1 个答案:

答案 0 :(得分:11)

我不确定原因,但似乎让aiohttp.ClientResponse对象保持打开状态会导致在解释器退出时抛出不可注意的异常。在我的系统上,这会产生类似这样的警告,而不是""消息:

sys:1: ResourceWarning: unclosed <socket object at 0x7f44fce557a8>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fce55718>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fcc24a78>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fcc248c8>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fcc24958>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fcc249e8>
sys:1: ResourceWarning: unclosed <socket object at 0x7f44fcc24b08>

在任何情况下,您都可以通过调用ClientResponse明确关闭fetch_objects末尾的response.close()对象来解决问题。