0

I have a function

async def hello(a): await asyncio.sleep(2) print(a) 

I want to call this function for several elements in a list asynchronously

list = ['words','I','need','to','print','parallely'] 

Something like this, but the below code runs one after the other.

for word in list: await hello(word) 

Is there a better way to do this? I had used asyncio.create_task but not sure how to use them in loops.

1
  • Do not use list as a variable name, it shadows built-in type list. Commented Dec 20, 2020 at 12:39

1 Answer 1

4

This is an example of how it should work:

import asyncio list_1 = 'hi i am cool'.split() async def hello(a): await asyncio.sleep(2) print(a) async def run_tasks(): tasks = [hello(word) for word in list_1] await asyncio.wait(tasks) def main(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(run_tasks()) loop.close() main() 

Sample output:

am i cool hi 

The above code is mainly for demonstration but the new and easier way to do so is:

def main2(): asyncio.run(run_tasks()) main2() 

Sample output:

i hi cool am 

Note:

As suggested in the comments, to preserve the order of inputs, define run_tasks as:

async def run_tasks(): tasks = [hello(word) for word in list_1] await asyncio.gather(*tasks) 
Sign up to request clarification or add additional context in comments.

5 Comments

To preserve the order of inputs, can use asyncio.gather(*tasks).
is that waht you meant?
Yes. If you run that, it should print "hi" "I" "am" "cool" in order.
RuntimeError: Cannot run the event loop while another loop is running Getting this error for the same code given above while running main()
import nest_asyncio nest_asyncio.apply() added these two lines and its working! thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.