我有两个 StreamReader
对象,想循环读取它们。我正在像这样使用 asyncio.wait
:
done, pending = await asyncio.wait(
[reader.read(1000), freader.read(1000)],
return_when=asyncio.FIRST_COMPLETED)
现在 done.pop()
给我第一个完成的 future 。问题是我不知道如何找到完成了哪个 read()
操作。我尝试将 [reader.read(1000), freader.read(1000)]
放入 tasks
变量中,并将完成的 future 与那些进行比较。但这似乎是不正确的,因为完成的 future 等于没有任何原始任务。那么我应该如何找到哪个协程已完成?
最佳答案
您需要为每个 .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
文档。
关于python - 如何知道哪些协程已通过 asyncio.wait() 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34509586/