Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from functions that run as asyncio tasks

I was trying the following code:

import asyncio  @asyncio.coroutine def func_normal():         print("A")         yield from asyncio.sleep(5)         print("B")         return 'saad'  @asyncio.coroutine def func_infinite():     i = 0     while i<10:         print("--"+str(i))         i = i+1     return('saad2')  loop = asyncio.get_event_loop()  tasks = [     asyncio.async(func_normal()),     asyncio.async(func_infinite())]  loop.run_until_complete(asyncio.wait(tasks)) loop.close() 

I can't figure out how to get values in variables from these functions. I can't do this:

asyncio.async(a = func_infinite()) 

as this would make this a keyword argument. How do I go about accomplishing this?

like image 822
Saad Aleem Avatar asked Sep 08 '15 11:09

Saad Aleem


People also ask

What does Asyncio run return?

Running an asyncio Program Execute the coroutine coro and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop, finalizing asynchronous generators, and closing the threadpool.

What Asyncio gather returns?

The asyncio. gather() returns the results of awaitables as a tuple with the same order as you pass the awaitables to the function.

What does Asyncio run do?

asyncio. run() , introduced in Python 3.7, is responsible for getting the event loop, running tasks until they are marked as complete, and then closing the event loop.


1 Answers

The coroutines work as is. Just use the returned value from loop.run_until_complete() and call asyncio.gather() to collect multiple results:

#!/usr/bin/env python3 import asyncio  @asyncio.coroutine def func_normal():     print('A')     yield from asyncio.sleep(5)     print('B')     return 'saad'  @asyncio.coroutine def func_infinite():     for i in range(10):         print("--%d" % i)     return 'saad2'  loop = asyncio.get_event_loop() tasks = func_normal(), func_infinite() a, b = loop.run_until_complete(asyncio.gather(*tasks)) print("func_normal()={a}, func_infinite()={b}".format(**vars())) loop.close() 

Output

--0 --1 --2 --3 --4 --5 --6 --7 --8 --9 A B func_normal()=saad, func_infinite()=saad2 
like image 69
jfs Avatar answered Oct 05 '22 20:10

jfs