[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段
Posted qyxfzmbz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段相关的知识,希望对你有一定的参考价值。
找了半天没找到原因,记录一下
操作系统:windows 8.1
python版本:python 3.8.1
aiohttp版本:3.6.2
源码:
1 import asyncio 2 import aiohttp 3 4 5 async def aiohttp_request_test(url): 6 async with aiohttp.request(‘get‘, url=url) as resp: 7 await resp.text() 8 # await asyncio.sleep(1) # A1 9 10 11 async def main(): 12 await asyncio.gather(aiohttp_request_test(‘https://www.baidu.com‘)) 13 14 15 asyncio.run(main()) 16 # loop = asyncio.get_event_loop() 17 # loop.run_until_complete(main())
运行以上代码时,出现如下异常:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x02A8C8E0> Traceback (most recent call last): File "D:PythonAnaconda3envspython38libasyncioproactor_events.py", line 116, in __del__ self.close() File "D:PythonAnaconda3envspython38libasyncioproactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "D:PythonAnaconda3envspython38libasyncioase_events.py", line 715, in call_soon self._check_closed() File "D:PythonAnaconda3envspython38libasyncioase_events.py", line 508, in _check_closed raise RuntimeError(‘Event loop is closed‘) RuntimeError: Event loop is closed
但是在第8行处加上一句await asyncio.sleep(1)后,无异常(方案A)
或者将
asyncio.run(main())
改为:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
也无异常。(方案B)
(实际使用的时候方案B也会出现上述异常,但这里未能复现,且也可用方案A解决)
我就很奇怪为什么加上一句await asyncio.sleep(1)就不报错了
还有,如果request抛出了一个异常并被捕获的话(将aiohttp_request_test改为如下):
async def aiohttp_request_test(url): try: async with aiohttp.request(‘get‘, url=url) as resp: await resp.text() except: pass
则也不会报RuntimeError: Event loop is closed
困了,找到原因了再回来补充。
以上是关于[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段的主要内容,如果未能解决你的问题,请参考以下文章
(Python)asyncio使用异常:This event loop is already running解决方式
我如何将crossbar客户端(python3,asyncio)与tkinter集成
Python websockets 服务器和 websockets 客户端在运行这两个任务时使用 asyncio 断言错误