Python程序输入Exit/exit陷入循环无法退出,求排查解决
问题原因
你的代码里的except:会捕获所有异常,包括exit()函数触发的SystemExit异常。当输入Exit/exit时,执行exit()会抛出SystemExit,但这个异常被except:捕获,程序进入错误提示流程并继续循环,无法正常退出。
修复方案
方案一:捕获特定异常(推荐)
只捕获文件打开失败的FileNotFoundError,不拦截程序退出的异常:
while True: try: fname = input('Enter a file name: ') if fname.lower().strip() == 'exit': exit() fhand = open(fname) break except FileNotFoundError: print(f'The file, {fname}, could not be located. Please enter another file name or type "Exit" to exit the application.') continue count = 0 for line in fhand: print(line.rstrip().upper()) count += 1 if count > 4: break
方案二:保留全局捕获但排除退出异常
如果需要捕获其他未知异常,可以在except:前单独处理SystemExit,重新抛出以让程序退出:
while True: try: fname = input('Enter a file name: ') if fname.lower().strip() == 'exit': exit() fhand = open(fname) break except SystemExit: raise except: print(f'The file, {fname}, could not be located. Please enter another file name or type "Exit" to exit the application.') continue count = 0 for line in fhand: print(line.rstrip().upper()) count += 1 if count > 4: break
额外说明
exit()函数通过抛出SystemExit异常实现程序终止,这是Python的标准行为。避免使用无限制的except:,因为它会拦截所有异常(包括系统退出、键盘中断等),导致程序行为不符合预期。
内容的提问来源于stack exchange,提问作者The Tree Code
相关产品推荐
相关产品推荐

