在 python 3.8 中使用 aiohttp 和 asyncio 关闭异常事件循环

Exception event loop is closed with aiohttp and asyncio in python 3.8

我正在使用 asyncio 和 aiohttp 发出并发请求。我最近将 Python 升级到版本 3.8.0,并且在程序 运行.

之后我得到一个 RuntimeError: Event loop is closed
import asyncio
import aiohttp

async def do_call(name, session):
    async with session.get('https://www.google.be') as response:
        await response.text()
        return 'ok - {}'.format(name)

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [do_call(str(i), session) for i in range(0,4)]
        results = await asyncio.gather(*tasks)
        print(results)

asyncio.run(main())

我确实从 asyncio.gather() 得到了有效结果,但在退出时引发了异常。 我想更改代码,使其不会 运行 成为异常。

回溯如下:

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001E9A92079D0>
Traceback (most recent call last):
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 711, in call_soon
    self._check_closed()
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 504, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed`

我认为这很可能是 aiohttp 错误。具体来说,我在他们的 github 上发现了这个问题:https://github.com/aio-libs/aiohttp/issues/4324

我知道这不一定对你有帮助,但也许你可以转回去,停止用头撞墙。你的代码没问题!

我通过在使用完后不调用 my_loop.close() 来解决这个问题。以这种方式关闭事件循环会导致错误被抛出,即使在我得到了我期望的所有响应之后也是如此。