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

标签 python python-2.4

在 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/

相关文章:

python - 列表内列表python

python - 线程代码在调用 FFI 进程时崩溃

python - 2.4 中的列表理解

python - 循环内循环 python

Python 2.4 内联 if 语句

python - 为什么我只能使用一次阅读器对象?

python 3 : import another function in python file: No module named load

python - 如何将列表元素附加到 Pandas 系列中的每一行?

python - 有效地更新计时器并在 python 中满足检查条件

python - 如何使用 matplotlib 的 LaTeX 格式化程序格式化 float ?