等待 asyncio.Future 会引发并发.futures._base.CancelledError,而不是等待设置值/异常

2024-01-09

当我运行以下 python 代码时:

import asyncio
import logging
logging.basicConfig(level=logging.DEBUG)

async def read_future(fut):
    print(await fut)

async def write_future(fut):
    fut.set_result('My Value')

async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    asyncio.gather(read_future(fut), write_future(fut))

asyncio.run(main(), debug=True)

代替read_future等待结果fut设置后,程序崩溃并出现以下错误:

DEBUG:asyncio:Using selector: KqueueSelector
ERROR:asyncio:_GatheringFuture exception was never retrieved
future: <_GatheringFuture finished exception=CancelledError() created at /Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/tasks.py:642>
source_traceback: Object created at (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/base_events.py", line 566, in run_until_complete
    self.run_forever()
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/base_events.py", line 534, in run_forever
    self._run_once()
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/base_events.py", line 1763, in _run_once
    handle._run()
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "<stdin>", line 4, in main
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/tasks.py", line 766, in gather
    outer = _GatheringFuture(children, loop=loop)
  File "/Users/<user>/.pyenv/versions/3.7.4/lib/python3.7/asyncio/tasks.py", line 642, in __init__
    super().__init__(loop=loop)
concurrent.futures._base.CancelledError
DEBUG:asyncio:Close <_UnixSelectorEventLoop running=False closed=False debug=True>

我在这段代码中做错了什么?我希望能够等待未来fut并在 Future 设置了值/异常后继续。


你的问题是asyncio.gather本身是异步的 https://docs.python.org/3/library/asyncio-task.html#asyncio.gather(返回一个可等待的);不通过await调用它时,您从未将控制权交还给事件循环,也没有存储可等待的内容,因此它立即被清理,隐式取消它,并且通过扩展,它控制的所有可等待的内容。

要修复,只需确保您await的结果gather:

await asyncio.gather(read_future(fut), write_future(fut))

在线尝试一下! https://tio.run/##ZY@7DsIwDEX3fEU2Ugl1YUPqwkNMbMBaheIGSyGpUoeqX19c2vLM4sQ39/q4aunq3aLr8Fb5QFLXrSvQi/FpvTHojBhretY1FmvvSjTKwh1sNimb7eq4S4R4BsgLlDKAvuRlpBhAcUmWQvKpAjpSutFIsu9@OpqABP8WvqU1UB6gjpbUbN/Kk7YRZl/mm0anRof1vpLZtExqenN0jjnzXlLJlMuf@kZaMOx79CAPjK8MTVcI6nep@T/0RMUmHqoGrjkznqPJDiFC0nUP

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

等待 asyncio.Future 会引发并发.futures._base.CancelledError,而不是等待设置值/异常 的相关文章

随机推荐