找了半天没找到原因,记录一下
操作系统: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:\Python\Anaconda3\envs\python38\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "D:\Python\Anaconda3\envs\python38\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "D:\Python\Anaconda3\envs\python38\lib\asyncio\base_events.py", line 715, in call_soon
self._check_closed()
File "D:\Python\Anaconda3\envs\python38\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
但是在第8行处加上一句await asyncio.sleep(1)后,无异常(方案A)
或者将
改为:
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
困了,找到原因了再回来补充。
-----------------------------------------------------------分割线-----------------------------------------------------------
在aiohttp官方文档找到一个疑似的原因:https://docs.aiohttp.org/en/latest/client_advanced.html#graceful-shutdown |