0

I have a piece of code like this:

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) 

I want to stop the loop process when "EUREEKA" appears. I use return but it doesn't stop either. What is the correct way to stop it? result of code

2
  • It stops, but you're creating multiple tasks, not just one. Commented May 30, 2021 at 9:15
  • @ŁukaszKwieciński how to stop another task? Commented May 31, 2021 at 0:54

1 Answer 1

1

asyncio.gather will wait for all tasks to complete. If you want to stop on first task that reaches the finish line, you can use 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() 
Sign up to request clarification or add additional context in comments.

2 Comments

what inside in t?
@AlfianAP In both loops t holds instances of asyncio.Task, itself a subclass of asyncio.Future.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.