Elektito
Elektito

Reputation: 4155

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?

Upvotes: 7

Views: 4564

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122023

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.

Upvotes: 12

Related Questions