Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Asyncio does not handle nested KeyboardInterrupt correctly #146194

Copy link
Copy link
@user202729

Description

@user202729
Issue body actions

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

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
    No fields configured for issues without a type.

    Projects

    Status
    Todo
    Show more project fields

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.