How to find out which coroutines were executed using asyncio.wait ()

I have two StreamReader and you want to read them in a loop. I use asyncio.wait as follows:

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

Now done.pop() gives me a future that ended first. The problem is that I don’t know how to find which read() operation completed. I tried to put [reader.read(1000), freader.read(1000)] in the tasks variable and compare the future with this. But this seems wrong, since the future made is not equal to any of the initial tasks. So how should I find which coroutine is complete?

+5
source share
1 answer

You need to create a separate task for each .read call and pass these tasks to .wait . Then you can 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 this example from the websockets documentation.

+5
source

Source: https://habr.com/ru/post/1239418/


All Articles