Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / Python

asyncio.CancelledError

Sporoči preklic ob naslednji priložnosti za nadaljevanje opravila po cancel().

Različica: Python 3.14; repository image, production runtime not attested

Sintaksa

except asyncio.CancelledError:

Sporoči preklic ob naslednji priložnosti za nadaljevanje opravila po cancel().

Namerno zatiranje izjeme ne ponastavi cancelling(). Za popolno odstranitev stanja uncancel() zmanjša števec za eno zahtevo. Deduje od BaseException in je except Exception ne ujame. Počistite v finally in izrecno ujeto izjemo navadno ponovno sprožite.

V primeru await zazna preklic in cancelled() po širjenju izjeme vrne True.

import asyncio
async def main():
    cleaned = []
    async def worker():
        try:
            await asyncio.Event().wait()
        finally:
            cleaned.append(True)
    t = asyncio.create_task(worker())
    await asyncio.sleep(0)
    t.cancel()
    try:
        await t
    except asyncio.CancelledError:
        assert t.cancelled() and cleaned == [True]
    assert not issubclass(asyncio.CancelledError, Exception)
asyncio.run(main())
import asyncio
async def main():
    t = asyncio.current_task()
    t.cancel()
    try:
        await asyncio.sleep(0)
    except asyncio.CancelledError:
        assert t.cancelling() == 1 and t.uncancel() == 0
asyncio.run(main())

Primeri

import asyncio

async def main():
    task = asyncio.create_task(asyncio.sleep(60))
    await asyncio.sleep(0)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print(task.cancelled())

asyncio.run(main())

Rezultat

True

V primeru await zazna preklic in cancelled() po širjenju izjeme vrne True.

Viri