Why is the CancelledError
not caught in this example?
import asyncio
q = asyncio.Queue()
async def getter():
try:
v = await q.get()
print(f"getter got {v}")
except asyncio.CancelledError:
print("getter cancelled")
async def test():
task = asyncio.ensure_future(getter())
task.cancel()
await task
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
if __name__ == '__main__':
main()
I excpected to get the "getter cancelled" message, but received a stack trace instead:
Traceback (most recent call last): File "ce.py", line 22, in main() File "ce.py", line 19, in main loop.run_until_complete(test()) File "/usr/lib64/python3.6/asyncio/base_events.py", line 468, in run_until_complete return future.result() concurrent.futures._base.CancelledError
Task.cancel states:
This arranges for a CancelledError to be thrown into the wrapped coroutine on the next cycle through the event loop. The coroutine then has a chance to clean up or even deny the request using try/except/finally.