10

我正在运行以下代码,它通过 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:

注意:没有关于异常是什么/在哪里的其他信息。

是什么原因造成的,是否有任何调试提示?

4

1 回答 1

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().

于 2015-04-07T23:33:30.560 回答