只捕获*一个* KeyboardInterrupt 异常

Catching only *one* KeyboardInterruptException

我有一个很长的 运行 任务可能会被中断,因为它内部引发了异常,或者因为按下了 Control+C 发出信号 SIGINT,养一个KeyboardInterruptException

在这两种情况下,要遵循的路径是存储任务已经处理的结果,以防止计算时间的损失。这家商店需要一些时间,因为它可能需要处理大量信息。当中断已经被捕获时,当 Control+C 再次按下 时出现问题。

示例:

task = SomeTask()
try:
    task.start()
except KeyboardInterruptException:
    print("Keyboard interrupted")
except Exception as e:
    print_exception(e) # To show what happened
finally:
    task.store_results() # If Control-C is pressed here, data gets corrupted

我需要一种方法来捕捉中断,启动存储进程并且防止另一个中断发生。

只需设置信号处理程序:

import signal

task = SomeTask()
try:
    task.start()
except KeyboardInterruptException:
    print("Keyboard interrupted")
except Exception as e:
    print_exception(e) # To show what happened
finally:
    signal.signal(signal.SIGINT, lamda *_: print('Wait!'))
    task.store_results() # If Control-C is pressed here, data gets corrupted

来源:https://pythonadventures.wordpress.com/2012/11/21/handle-ctrlc-in-your-script/