
KeyboardInterrupt是 Python 中用于处理用户中断操作的异常。当用户按下CtrlCWindows/Linux/macOS或CtrlZ某些系统时Python 会抛出这个异常。一、KeyboardInterruptKeyboardInterrupt继承自BaseException不是Exception意味着它不会被普通的except Exception捕获。import time try: while True: print(运行中...) time.sleep(1) except KeyboardInterrupt: print(\n用户中断了程序)当用户按下CtrlC时输出运行中... 运行中... ^C 用户中断了程序二、为什么它不在 Exception 体系里print(issubclass(KeyboardInterrupt, Exception)) # False print(issubclass(KeyboardInterrupt, BaseException)) # True原因KeyboardInterrupt代表的是用户主动中断通常不应被普通异常处理逻辑吞掉。# 错误会捕获 KeyboardInterrupt导致 CtrlC 无法退出 try: while True: time.sleep(1) except Exception: print(捕获了所有异常) # 这会把 KeyboardInterrupt 也吃掉CtrlC 无法退出 # 正确区分处理 try: while True: time.sleep(1) except KeyboardInterrupt: print(用户中断) except Exception as e: print(f其他异常: {e})三、捕获 KeyboardInterrupt1. 基本捕获import time def main(): try: print(按 CtrlC 退出) while True: print(工作中...) time.sleep(0.5) except KeyboardInterrupt: print(\n程序已退出) # 可以在这里做清理工作 # 关闭文件、释放资源等 if __name__ __main__: main()2. 如果不捕获程序会在CtrlC时直接退出import time while True: print(运行中...) time.sleep(1) # 按下 CtrlC → 程序直接终止不执行任何清理