2

I'm using a python API wrapper with async functions. I need to call the API several times and would like to override the async functionality by waiting for each task to complete before moving on to the next iteration.

import asyncio loop = asyncio.get_event_loop() for count in range(5): loop.create_task(main(count)) # Need this line to complete before next iteration time.sleep(60) # Hacky solution 

Currently I'm just sleeping until I can assume main() is complete. How can I ensure main() never runs concurrently with itself?

1 Answer 1

2

To wait for the task to finish, use await. This requires an async function, which you can run using asyncio.run:

async def x(): for count in range(5): await main(count) asyncio.run(x()) 

If you want to do the same from top-level code, just call run_until_complete as many times as needed:

loop = asyncio.get_event_loop() for count in range(5): loop.run_until_complete(main(count)) 
Sign up to request clarification or add additional context in comments.

2 Comments

When I do run_until_complete I get RuntimeError: This event loop is already running, which I can fix by also using nest_asyncio, but I am curious if there's a native way to do it.
@Jeremy414 How are you running your code, as a script or in a console?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.