gpt4 book ai didi

python - 避免在 Python 2.4 中意外捕获 KeyboardInterrupt 和 SystemExit

转载 作者:IT老高 更新时间:2023-10-28 21:13:43 25 4
gpt4 key购买 nike

在 Python 脚本中,由于代码中某处的 except 子句,在很多情况下键盘中断 (Ctrl-C) 无法终止进程:

try:
foo()
except:
bar()

Python 2.5 或更高版本中的标准解决方案是捕获 Exception 而不是使用裸 except 子句:

try:
foo()
except Exception:
bar()

这是因为,从 Python 2.5 开始,KeyboardInterruptSystemExit 继承自 BaseException,而不是 Exception。但是,某些安装仍在运行 Python 2.4。在 Python 2.5 之前的版本中如何处理这个问题?

(我将自己回答这个问题,但把它放在这里以便搜索它的人可以找到解决方案。)

最佳答案

根据Python documentation ,在 2.5 之前的 Python 版本中处理这个问题的正确方法是:

try:
foo()
except (KeyboardInterrupt, SystemExit):
raise
except:
bar()

这很罗嗦,但至少这是一个解决方案。

关于python - 避免在 Python 2.4 中意外捕获 KeyboardInterrupt 和 SystemExit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com