Skip to content

Asyncio does not handle nested KeyboardInterrupt correctly #146194

Closed as not planned

Description

@user202729

Bug report

Bug description:

Consider this code

import sys
import logging
import asyncio
import signal
from time import*

logger = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO)

async def f():
    if 1:
        main_task = asyncio.current_task()
        def on_sigint() -> None:
            logger.error("Received SIGINT")
            main_task.cancel(KeyboardInterrupt)
        asyncio.get_running_loop().add_signal_handler(signal.SIGINT, on_sigint)
    try:
        while True:
            await asyncio.sleep(0.1)
            print("*")
    except asyncio.CancelledError as e:
        print(e)
        try:
            while True:
                await asyncio.sleep(0.1)
                print("#")
        except asyncio.CancelledError:
            try:
                while True:
                    await asyncio.sleep(0.1)
                    print("!")
            except asyncio.CancelledError:
                while True:
                    await asyncio.sleep(0.1)
                    print("@")

asyncio.run(f())

Intention: each time I press Ctrl-C, it repeatedly print *, #, !, @ respectively.

As is, it does do that correctly.

However, if I don't manually add the SIGINT signal handler, it will print *, {first Ctrl-C} #, {second Ctrl-C} !, {third Ctrl-C} then forcefully stop.

I don't think this behavior is desirable. Or at least it probably shouldn't log a scary error Task was destroyed but it is pending!?

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added 2 commits that reference this issue on Mar 20, 2026
  2. added 2 commits that reference this issue on Mar 20, 2026
  3. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Mar 20, 2026
  4. picnixz commented on Mar 20, 2026

    @picnixz
    Member

    @okiemute04 Please avoid using LLM for generating answers and do not claim that an issue is good to work on unless it has been triaged. This is the role of triagers and core devs.

    cc @kumaraditya303

  5. kumaraditya303 commented on Jul 31, 2026

    @kumaraditya303
    Contributor

    This is not a bug. By default if you press CTRL+C twice then you would break out of the loop with asyncio runner. This is a long standing behavior and should not be changed.

  6. moved this from Todo to Done in asyncioon Jul 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions