python - 如何知道哪些协程已通过 asyncio.wait() 完成

标签 python python-3.x python-asyncio

我有两个 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/

相关文章:

python - 如何使用 Ctrl+C 优雅地关闭协程?

python - python列表中值的有效比较

python - 根据值列 a 映射到列 b 获取列 c 创建新列

python - Python 中的 "chmod -R u+x $path"是什么?

python - 如何将 python 字典的键显示为 HTML 表头,并将每个键的值显示为该表头下的一行?

Python异步: is the error me or the API?

python - 导入错误 : No module named openerp

python - 使用 pandas GroupBy 聚合时设置 MultiIndex

python - 从 Python 中存储的字符串调用函数

python - asyncio的事件循环使用什么调度算法?