CancelledError is raised when a cancelled asyncio task is awaited. Cancellation is cooperative: calling cancel() does not interrupt ordinary Python code immediately. The exception appears at the current or next await point, if one exists. section 2.4.1
Stopping an overlong task
Create a ten-second task, check it once per second, and call cancel() after five seconds. Awaiting the task inside try/except CancelledError lets the application report that it stopped the operation. section 2.4.1
Listing 2.11 Canceling a task
import asyncio
from asyncio import CancelledError
from util import delay
async def main():
long_task = asyncio.create_task(delay(10))
seconds_elapsed = 0
while not long_task.done():
print('Task not finished, checking again in a second.')
await asyncio.sleep(1)
seconds_elapsed = seconds_elapsed + 1
if seconds_elapsed == 5:
long_task.cancel()
try:
await long_task
except CancelledError:
print('Our task was cancelled')
asyncio.run(main())
Runnable listing showing task creation, periodic status checks, cancellation, and CancelledError handling. section 2.4.1
