码迷,mamicode.com
首页 > 编程语言 > 详细

[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')

时间:2020-02-15 10:15:13      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:get   解决问题   报错   wait   func   pipe   self   base   port   

找了半天没找到原因,记录一下

操作系统: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

或者将

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')

标签:get   解决问题   报错   wait   func   pipe   self   base   port   

原文地址:https://www.cnblogs.com/qyxfzmbz/p/12310524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!