【发布时间】:2019-04-06 16:37:51
【问题描述】:
获取取消任务的句柄很容易:
task = loop.create_task(coro_fn())
# later
task.cancel()
是否可以对异步上下文管理器执行相同的操作?
async with foo() as bar:
# is it possible to cancel before getting here,
# while waiting to enter the context manager?
await bar.baz()
# later
# How do I get a handle to the context manager for cancellation?
有没有办法做到这一点?还是上下文管理器代码需要在自己的任务中运行?
【问题讨论】:
-
你到底想取消什么?
-
在上下文管理器的
__aenter__中执行暂停(可能正在等待获取资源)。我想取消它,以便asyncio.CancelledError从中得到提升。 -
您取消在
__aenter__中挂起的任务,就像在 asyncio 中的其他任何事情一样——通过确保它在任务中并在其上调用cancel()。详情见我的回答。
标签: python python-asyncio