📜  TypeError: ProactorEventLoop 不支持,得到:<ProactorEventLoop running=False closed=False debug=False> (1)

📅  最后修改于: 2023-12-03 14:48:04.229000             🧑  作者: Mango

错误介绍:Type Error: ProactorEventLoop 不支持

当使用 ProactorEventLoop 时,有可能会出现 Type Error: ProactorEventLoop 不支持 的错误提示。

以下是错误代码片段:

import asyncio

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://www.google.com") as resp:
            print(resp.status)

if __name__ == "__main__":
    asyncio.set_event_loop(asyncio.ProactorEventLoop())
    asyncio.run(main())

输出:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    asyncio.set_event_loop(asyncio.ProactorEventLoop())
  File "/usr/lib/python3.8/asyncio/events.py", line 703, in set_event_loop
    raise ValueError("loop argument must agree with Future class")
ValueError: loop argument must agree with Future class
原因分析

ProactorEventLoop 是 asyncio 的事件循环的一种实现,针对 Windows 平台的 I/O 模型,用于提高异步 I/O 的性能。但是,它并不支持所有的操作系统和 Python 版本。

在 Python 3.8 及以下版本和某些操作系统中,使用 ProactorEventLoop 可能会导致上述错误。

解决方案
  1. 更换 ProactorEventLoop 为默认的 asyncio 事件循环即可解决该问题。

修改错误代码片段如下:

import asyncio
import aiohttp

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://www.google.com") as resp:
            print(resp.status)

if __name__ == "__main__":
    asyncio.run(main())
  1. 或者,在 Python 3.9 及以上版本中,可以使用更先进的 SelectorEventLoop 代替 ProactorEventLoop,以获取更好的异步 I/O 性能。

修改错误代码片段如下:

import asyncio
import aiohttp

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://www.google.com") as resp:
            print(resp.status)

if __name__ == "__main__":
    asyncio.set_event_loop(asyncio.SelectorEventLoop())
    asyncio.run(main())

以上就是此错误的详细介绍和解决方案。建议在使用 asyncio 时,根据实际情况选择合适的事件循环。