首页 > 解决方案 > Windows 上的“RuntimeError:事件循环已关闭”

问题描述

我编写了这个简单的代码来使用 asyncio 和 aiohttp 获取一些 url。

import asyncio
import aiohttp


async def fetch(url, session):
    async with session.get(url) as response:
        return await response.read()


async def fetch_all(urls):
    tasks = []
    async with aiohttp.ClientSession() as session:
        for url in urls:
            task = asyncio.create_task(fetch(url, session))
            tasks.append(task)

        return await asyncio.gather(*tasks)


if __name__ == '__main__':
    res = asyncio.run(fetch_all(['http://www.youtube.com', 'http://www.google.com']))
    print(res)

我正在使用 Python 3.8 和 PyCharm,它在 MacOS 上运行良好。如果我尝试在 Windows 上运行它,它仍然可以工作,但是在打印结果后,它给了我

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x036ED2B0>
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 719, in call_soon
    self._check_closed()
  File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 508, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

但是,如果我替换asyncio.run()

loop = asyncio.get_event_loop()
res = loop.run_until_complete(fetch_all(['http://www.youtube.com', 'http://www.google.com']))
print(res)

它可以正常工作。可以使用这个选项吗?为什么会这样?

标签: python-3.xpython-asyncioaiohttp

解决方案


推荐阅读