如何知道哪些协程是用 asyncio.wait() 完成的

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

我有两个 StreamReader 对象,想循环读取它们。我正在使用 asyncio.wait 这样的:

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

现在done.pop()给我第一个完成的未来。问题是我不知道如何找到哪个 read() 操作完成了。我尝试将 [reader.read(1000), freader.read(1000)] 放入 tasks 变量中,并将完成的未来与那些进行比较。但这似乎是不正确的,因为完成的未来等于原始任务的 none。那么我应该如何找到哪个协程完成了呢?

您需要为每个 .read 调用创建一个单独的任务,并将这些任务传递给 .wait。然后您可以检查任务在结果中的位置。

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:
   ...

...

参见例如this example 来自 websockets 文档。