Python 2.7 ctrl+c 不确定行为

标签 python python-2.7 signals

我希望在我的脚本中进行正确的 CTRL+C 处理,我一直在阅读一些示例,但无法实现确定性行为。 例如,给定以下脚本:

  1 import signal
  2 import time
  3
  4 def sigint_handler(signum, frame):
  5     raise Exception('captured ctrl+c')
  6
  7 signal.signal(signal.SIGINT, sigint_handler)
  8
  9 c = True
 10 while c:
 11     try:
 12         pass
 13     except KeyboardInterrupt as e:
 14         print 'captured keyboardexception'
 15         print str(e)
 16     except Exception as e:
 17         print 'captured exception'
 18         print str(e)
 19         c = False

我可以获得这两个不同的输出

$ python ctrlc.py
^Ccaptured exception
captured ctrl+c

$ python ctrlc.py
^CTraceback (most recent call last):
  File "ctrlc.py", line 12, in <module>
    pass
  File "ctrlc.py", line 5, in sigint_handler
    raise Exception('captured ctrl+c')
Exception: captured ctrl+c

我尝试了不同的配置,也使用了双重异常处理并且没有信号处理,但您总是可以通过点击 CTRL+C

获得不同的行为

最佳答案

经典的竞赛条件。当你的循环展开时,它看起来像这样:

while True:
    ....
    try:
       pass      <-----
    ....

while True:      <-----
    ....
    try:
        pass

在箭头之间的时间里,您实际上并不处于 try/except 子句中。所以你应该期待两种不同的行为。

试试这个:

try:
    while True:
         pass
except....

关于Python 2.7 ctrl+c 不确定行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519195/

相关文章:

python - Flask/SQLAlchemy : Incompatible collection type: None is not list-like

python - 我可以做一个 django 获取最新版本 ==

Python:迭代条件内的预定条件

swift - 断言代码在单元测试中的某个时刻运行?

c - 为什么这个程序在 ubuntu windows 桌面应用程序和 ubuntu 虚拟盒子上给出不同的输出?

python - 删除市场数据中的重复项

Python: Pandas, Dataframe, 将一列数据转换成二维数据格式

python - 在 XML 文档中搜索命名空间中的元素

python - 如何使用 python 的标准库 zipfile 检查 zip 文件是否加密?

linux - 使用 SIGALRM 和计时器时内存损坏