Python Asyncio任务取消 [英] Python Asyncio Task Cancellation
问题描述
我正在阅读asyncio文档以了解任务取消,并且遇到了此-
I was reading asyncio documentation for task cancel and I came across this -
要取消正在运行的Task,请使用cancel()方法.调用它将导致Task向包装的协程中抛出CancelledError异常.如果协程在取消过程中等待Future对象,则Future对象将被取消.
To cancel a running Task use the cancel() method. Calling it will cause the Task to throw a CancelledError exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.
cancelled()可用于检查任务是否已取消.如果包装的协程没有抑制CancelledError异常并确实被取消,则该方法返回True.
cancelled() can be used to check if the Task was cancelled. The method returns True if the wrapped coroutine did not suppress the CancelledError exception and was actually cancelled.
我在这里有几个问题-
-
包装的协程是否被称为cancel的协程?让我们在这里举个例子-
Is wrapped coroutine the coroutine in which cancel is called? Let's take an example here -
async def wrapped_coroutine():
for task in asyncio.Task.all_tasks():
task.cancel()
那么 wrapped_coroutine()
是包装好的协程,任务将在该协程中抛出异常?
So wrapped_coroutine()
is the wrapped coroutine where task will throw an exception?
何时将引发此异常?在哪里?
When will this exception be thrown? And where?
抑制异常在这里意味着什么?这是否意味着-
What does suppress the exception mean here? Does it mean this -
async def wrapped_coroutine():
for task in asyncio.Task.all_tasks():
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task cancelled")
如果没有,请提供一个示例来说明如何抑制此异常.
If not, please provide an example on how to suppress this exception.
还有一个不相关的(与取消任务有关),当我取消这些任务时如何从这些任务中检索异常,所以我看不到-
And an unrelated(it's related to cancelling tasks), how do I retrieve exceptions out of these tasks when I'm cancelling these so I don't see this -
Task exception was never retrieved future:
是在 task.cancel()
之前还是在 await任务
之前的 try
中(在上面的示例中)?
Is it before task.cancel()
or in try
before await task
(in the above example) ?
推荐答案
查看文档
回答您的问题: 这篇关于Python Asyncio任务取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
否,这里的包装好的协程是 cancel_me()
;在 main()
中调用 .cancel()
.
在调用 task.cancel()
之后,将引发此异常.它被扔进协程中,在示例中被捕获,然后重新引发以被抛出并陷入等待的例程中.
如果 cancel_me()
在捕获到异常后不会重新引发该异常.正如 cancelled()
的文档所述:当使用cancel()请求取消时,任务被取消,并且包装的协程将抛出的CancelledError异常传播到其中." https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelled
No, the wrapped coroutine here is cancel_me()
; .cancel()
is called in main()
.
This exception is thrown after task.cancel()
is called. It is thrown inside the coroutine, where it is caught in the example, and it is then re-raised to be thrown and caught in the awaiting routine.
If cancel_me()
would not have re-raised the exception after catching it. As the documentation of cancelled()
states: "The Task is cancelled when the cancellation was requested with cancel() and the wrapped coroutine propagated the CancelledError exception thrown into it." https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancelled