Python中如何防止一段代码被KeyboardInterrupt打断?

新手上路,请多包涵

dump 操作正在保存数据时按 ctrl + c ,中断导致文件损坏(即仅部分写入,因此不能 load 再次编辑。

有没有办法使 dump 或一般的任何代码块不间断?


我当前的解决方法如下所示:

 try:
    file = open(path, 'w')
    dump(obj, file)
    file.close()
except KeyboardInterrupt:
    file.close()
    file.open(path,'w')
    dump(obj, file)
    file.close()
    raise

中断了就重新开始运行好像很傻,那中断怎么延迟呢?

原文由 saffsd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 533
2 个回答

将函数放在一个线程中,并等待线程完成。

除非使用特殊的 C api,否则不能中断 Python 线程。

 import time
from threading import Thread

def noInterrupt():
    for i in xrange(4):
        print i
        time.sleep(1)

a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"

0
1
2
3
Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\test.py", line 11, in <module>
    a.join()
  File "C:\Python26\lib\threading.py", line 634, in join
    self.__block.wait()
  File "C:\Python26\lib\threading.py", line 237, in wait
    waiter.acquire()
KeyboardInterrupt

看到中断是如何延迟到线程完成的吗?

此处适合您的使用:

 import time
from threading import Thread

def noInterrupt(path, obj):
    try:
        file = open(path, 'w')
        dump(obj, file)
    finally:
        file.close()

a = Thread(target=noInterrupt, args=(path,obj))
a.start()
a.join()

原文由 Unknown 发布,翻译遵循 CC BY-SA 2.5 许可协议

以下是为 SIGINT 附加信号处理程序的上下文管理器。如果调用上下文管理器的信号处理程序,则在上下文管理器退出时,通过仅将信号传递给原始处理程序来延迟信号。

 import signal
import logging

class DelayedKeyboardInterrupt:

    def __enter__(self):
        self.signal_received = False
        self.old_handler = signal.signal(signal.SIGINT, self.handler)

    def handler(self, sig, frame):
        self.signal_received = (sig, frame)
        logging.debug('SIGINT received. Delaying KeyboardInterrupt.')

    def __exit__(self, type, value, traceback):
        signal.signal(signal.SIGINT, self.old_handler)
        if self.signal_received:
            self.old_handler(*self.signal_received)

with DelayedKeyboardInterrupt():
    # stuff here will not be interrupted by SIGINT
    critical_code()

原文由 Gary van der Merwe 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏