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

Python输入阶段中断程序时如何避免崩溃并正常退出?

处理Python输入等待时的KeyboardInterrupt异常,实现正常退出

直接给你能解决问题的代码,把输入逻辑包裹在try-except块里,捕获KeyboardInterrupt后指定退出码即可:

import sys

try:
    user_input = input('enter: ')
    print(user_input)
except KeyboardInterrupt:
    # 按需设置退出码,0为正常结束,-1为异常终止
    sys.exit(0)

为什么之前的try-except没生效?

大概率是你没把input()语句完整放进try块里,或者捕获的异常类型不对。当程序在输入等待时被中断,input()会直接抛出KeyboardInterrupt,只要把这段逻辑包裹在try范围内,就能正常捕获。

如果不需要额外处理,也可以简化成这样:

import sys

try:
    user_input = input('enter: ')
    print(user_input)
except KeyboardInterrupt:
    sys.exit(-1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:47:02