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

为何输入exit()后Python代码陷入无限循环?

问题分析与解决

先贴出你的代码:

executed = False

while executed == False:
    try:
        inp = input("Enter the variable you want to change (e.g.: limit = 10): ")
        eval(inp, globals())
    except:
        print("Invalid input")
        continue
    print("Variable has been changed")
    executed = True

为什么输入exit()会触发无限循环?

当你输入exit()执行时,eval(inp, globals())会调用exit()函数——这个函数本质是抛出SystemExit异常,用来终止程序。

但你的代码用了裸except:(捕获所有异常),把SystemExit也拦下来了,程序没终止,反而执行print("Invalid input")后用continue回到循环开头。

更关键的是:exit()执行后,标准输入流(stdin)会被置为EOF(文件结束)状态。后续再调用input()时,因为没有任何输入可读,会直接抛出EOFError异常,而这个异常又被裸except:捕获,导致循环无限重复:每次跳过输入等待,直接打印"Invalid input",周而复始。

解决办法

1. 只捕获特定异常

把裸except:改成捕获输入不合法的特定异常(比如语法错误、未定义变量),让SystemExit和EOFError正常终止程序:

executed = False

while executed == False:
    try:
        inp = input("Enter the variable you want to change (e.g.: limit = 10): ")
        eval(inp, globals())
    except (SyntaxError, NameError):  # 仅处理输入语法或变量不存在的异常
        print("Invalid input")
        continue
    print("Variable has been changed")
    executed = True

2. 单独处理exit命令

在执行eval前判断输入是否为exit(),直接终止程序:

executed = False

while executed == False:
    try:
        inp = input("Enter the variable you want to change (e.g.: limit = 10): ")
        if inp.strip() == "exit()":
            exit()
        eval(inp, globals())
    except:
        print("Invalid input")
        continue
    print("Variable has been changed")
    executed = True

3. 排除终止类异常

如果一定要用宽范围捕获,手动排除SystemExit和EOFError,让程序正常终止:

executed = False

while executed == False:
    try:
        inp = input("Enter the variable you want to change (e.g.: limit = 10): ")
        eval(inp, globals())
    except (SystemExit, EOFError):
        raise  # 重新抛出异常,让程序正常终止
    except:
        print("Invalid input")
        continue
    print("Variable has been changed")
    executed = True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:33:13