为什么异步循环不能停止?

Why asyncio loop cant stop?

我有一段代码是这样的:

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 但它也不会停止。停止它的正确方法是什么? result of code

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()