python - 为什么异步循环不能停止?
问题描述
我有一段这样的代码:
import asyncio
import aiohttp
from time import process_time
ts = process_time()
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def bot(s):
async with s.get('https://httpbin.org/uuid') as r:
resp = await r.json()
print(resp['uuid'][0])
if resp['uuid'][0] == '0':
print("EUREEKA")
return
async def main():
async with aiohttp.ClientSession() as s:
await asyncio.gather(*[bot(s) for _ in range(0, 1000)])
if __name__ == "__main__":
asyncio.run(main())
te = process_time()
print(te-ts)
我想在出现“EUREEKA”时停止循环过程。我使用 return 但它也不会停止。阻止它的正确方法是什么?代码结果
解决方案
asyncio.gather
将等待所有任务完成。如果您想停止第一个到达终点线的任务,您可以使用asyncio.wait
with FIRST_COMPLETED
:
async def main():
async with aiohttp.ClientSession() as s:
done, pending = await asyncio.wait(
[bot(s) for _ in range(0, 1000)],
return_when=asyncio.FIRST_COMPLETED
)
# ensure we notice if the task that is done has actually raised
for t in done:
await t
# cancel the tasks that haven't finished, so they exit cleanly
for t in pending:
t.cancel()
推荐阅读
- html - 如何在按钮下放置一个下拉列表
- zabbix - Zabbix api 值与 Graph 值不同
- python - 计算向量的滑动平均值
- chart.js - 如何在chartjs quickchart io中选择图表上的上下文或比例来运行getValueForPixel?
- elasticsearch - 将区间查询转换为不支持的早期版本
- python - 如何在使用 SIMpleNLG 生成的句子中添加逗号
- java - 尝试在 Android 上导入 Excel XLSX 文件时出现 IOException
- javascript - Vue:当数据异步更改时 Radio 不会更新其值
- javascript - 如何从数组中删除数字( item )并仅显示字符串?使用香草js
- pivot-table - Excel 数据透视表平均汇总与分组数据不一致