栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

asyncio 警告 DeprecationWarning: There is no current event loop

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

asyncio 警告 DeprecationWarning: There is no current event loop

以下为实现异步抓取网页的代码段:

import asyncio
import aiohttp


async def fetch_page(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return response.status

tasks = [fetch_page('http://books.toscrape.com') for i in range(50)]

loop = asyncio.get_event_loop()

loop.run_until_complete(asyncio.gather(*tasks))

当前 Python 版本为 3.10.5,运行以上代码,会出现如下警告:

DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()
DeprecationWarning: There is no current event loop
  loop.run_until_complete(asyncio.gather(*tasks))

总之 asyncio.get_event_loop(), asyncio.gather(*tasks) 两个函数都不能用。

代码改为使用 asyncio.run() ,测试ok:

import asyncio
import aiohttp


async def fetch_page(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            print(response.status)


async def main():
    tasks = [fetch_page('https://quotes.toscrape.com/') for i in range(50)]
    await asyncio.gather(*tasks)  # argument unpacking: (tasks[0], tasks[1], ... tasks[49])

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

以下语句必须要加,

# important
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

否则 windows 系统对于 https 网站,会出现错误

RuntimeError: Event loop is closed
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号