python / python/cpython

`KeyboardInterrupt` not handled while evaluating a tight `while` loop condition on Python 3.13

未关闭
#130,279 6 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

@markshannon 已经在做这个了。

开始于 2025年2月19日。

3.13 interpreter-core type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

Consider the following infinite loop:

# test.py

class A:
    def __init__(self):
        self.shutdown_requested = False

    def start(self):
        pass

    def stop(self):
        self.shutdown_requested = True


def loop_1(a: A):
    try:
        while not a.shutdown_requested:
            pass

    except KeyboardInterrupt:
        print("in except block")

    finally:
        print("in finally block")
        a.stop()

def loop_2(a: A):
    try:
        while True:
            if a.shutdown_requested:
                break
    except KeyboardInterrupt:
        print("in except block")

    finally:
        print("in finally block")
        a.stop()


if __name__ == "__main__":
    a = A()
    a.start()
    loop_1(a)
    # loop_2(a)
^CTraceback (most recent call last):
  File "/home/harshil/test.py", line 40, in <module>
    loop_1(a)
    ~~~~~~^^^
  File "/home/harshil/test.py", line 14, in loop_1
    while not a.shutdown_requested:
              ^^^^^^^^^^^^^^^^^^^^
KeyboardInterrupt

If you run this program on Python 3.13 (3.13.1, and 3.13.2), pressing Ctrl+C does not execute the except and finally blocks in the case of loop_1(), but it works for loop_2().

If you run the same program on 3.14a5, or below 3.13, the issue does not happen, and the print statements are visible too.

CPython versions tested on:

3.12, 3.13, 3.13t, 3.14, 3.10

Operating systems tested on:

Linux

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。