首页 文章

aiohttp - 异常忽略的消息

提问于
浏览
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:

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

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

1 回答

  • 10

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

    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>
    

    在任何情况下,您都可以通过调用 response.close() 显式关闭 fetch_objects 末尾的 ClientResponse 对象来修复它 .

相关问题