You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

监控键盘输入时while循环中KeyboardInterrupt未按预期生效

解决msvcrt模块下无法捕获Ctrl+C的问题

你的代码存在两个核心问题导致无法捕获KeyboardInterrupt:

  1. kbhit是函数,你写成了if kbhit:,这是判断函数对象而非调用它,正确写法是if kbhit():
  2. Windows下msvcrt的getch/kbhit会绕过Python的信号处理机制,导致Ctrl+C无法触发KeyboardInterrupt异常

修复方案一:调整信号处理与循环结构

把try块包裹整个循环,同时添加短暂休眠让Python有机会处理中断信号,修复kbhit的调用:

from msvcrt import kbhit, getch
import time

def main():
    try:
        while True:
            if kbhit():
                key = getch()
                handle_keypress(key)
            time.sleep(0.01)  # 给信号处理留时间
    except KeyboardInterrupt:
        print("程序已退出")

def handle_keypress(key):
    if key == b"\t":
        print("按下了Tab键")
    elif key == b"\r":
        print("按下了回车键")
    elif key == b"\x1b":
        print("按下了Esc键")
    elif key == b" ":
        print("按下了空格键")

main()

修复方案二:手动识别Ctrl+C按键码

Ctrl+C对应的按键码是b'\x03',可以直接在按键处理逻辑中捕获并退出:

from msvcrt import kbhit, getch

def main():
    while True:
        if kbhit():
            key = getch()
            if key == b'\x03':  # 识别Ctrl+C
                print("程序已退出")
                break
            handle_keypress(key)

def handle_keypress(key):
    if key == b"\t":
        print("按下了Tab键")
    elif key == b"\r":
        print("按下了回车键")
    elif key == b"\x1b":
        print("按下了Esc键")
    elif key == b" ":
        print("按下了空格键")

main()

说明

方案一利用Python的原生信号处理,适合需要保留KeyboardInterrupt异常处理逻辑的场景;方案二更直接,通过识别按键码主动退出,避免信号处理的问题。

内容的提问来源于stack exchange,提问作者user30577847

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:40:59