Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which coroutines were done with asyncio.wait()

I have two StreamReader objects and want to read from them in a loop. I'm using asyncio.wait like this:

done, pending = await asyncio.wait(
    [reader.read(1000), freader.read(1000)],
    return_when=asyncio.FIRST_COMPLETED)

Now done.pop() gives me the future that finished first. The problem is I don't know how to find which read() operation completed. I tried putting [reader.read(1000), freader.read(1000)] in a tasks variable and comparing the done future with those. But this seems to be incorrect since the done future is equal to none of the original tasks. So how am I supposed to find which coroutine was finished?

like image 789
Elektito Avatar asked Dec 29 '15 10:12

Elektito


1 Answers

You need to create a separate task for each .read call, and pass those tasks to .wait. You can then check where the tasks are in the results.

reader_task = asyncio.ensure_future(reader.read(1000))
...

done, pending = await asyncio.wait(
    [reader_task, ...],
    return_when=asyncio.FIRST_COMPLETED,
)

if reader_task in done:
   ...

...

See e.g. this example from the websockets documentation.

like image 78
jonrsharpe Avatar answered Oct 31 '22 12:10

jonrsharpe