为什么异步循环不能停止



我有一段这样的代码:

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";出现。我使用回车,但它也不会停止。阻止它的正确方法是什么?代码结果

asyncio.gather将等待所有任务完成。如果你想在到达终点线的第一个任务上停止,你可以使用asyncio.waitFIRST_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()

最新更新