How to Solve asyncio CancelledError and KeyboardInterrupt in Python

asyncio CancelledError and KeyboardInterrupt in Python is an error which occurs when you try to Cancel a task.

This post is my attempt to explain to you why this error occurs and how you can solve it, I will also include multiple solutions that could be considered as alternative fixes to the error.

Explaining the Error : asyncio CancelledError and KeyboardInterrupt in Python

The error above occurs when you try to cancel a task in python

Just make sure the error message you are getting specifies asyncio CancelledError, just to make sure there is no confusion between the error you are having and the error we talked about.

These are the imports we have

                                                                       #
import asyncio
import aioredis
from functools import partial
                                                                       #

To solve the problem above, I have one solution which has worked for me, bellow is a detailed explanation of the solution.

Solution : Correctly using task.cancel().

The solution is simple, to stop an infinite loop from running you can call task.cancel() and await while the task is being cancelled ( while the CancelledError is being raised at the same time ).

Please do not suppress CancelledError inside the task.

In order to cancel your task and await it being cancelled you can try the code bellow.

                                                                       #
from contextlib import suppress
task = ...  # remember, task doesn't suppress CancelledError itself
task.cancel()  # returns immediately, we should await task raised CancelledError.
with suppress(asyncio.CancelledError):
await task
                                                                       #

We have awaited for CancelledError and handled it, the task is finally over and we can close the event loop without worrying about a warning.

Additionally, You can move loop.run_until_complete(kill_tasks()) into the last block, before loop.close().

The issue should be solved forever. The error should as a result be gone.

I hope the commands above fixed your problem, good luck with the scripts to come.

Summing-up

Here we are at the end of the road, at the end of this article, if you solved this error congrats, this was a confusing error for me the first time I encountered it. Make sure to keep coding and keep learning, Python is my favourite programming language, it just needs some patience, cheers.

If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/