如何“停止"和“恢复"长时间运行Python脚本? [英] How to "stop" and "resume" long time running Python script?

查看:304
本文介绍了如何“停止"和“恢复"长时间运行Python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了Python脚本,该脚本处理大量的大型文本文件,并且可能会运行时间.有时,需要停止正在运行的脚本并在以后恢复它.停止脚本的可能原因是程序崩溃,磁盘空间不足或需要执行此操作的其他原因.我想为脚本实现一种停止/恢复"机制.

I wrote Python script that processes big number of large text files and may run a lot of time. Sometimes, there is a need to stop the running script and to resume it later. The possible reasons to stop the script are program crash, disk 'out of space' situation or many others when you have to do it. I want to implement kind of "stop/resume" mechanism for the script.

  • 停止时:脚本退出&保存其当前状态.
  • 恢复上:脚本启动,但从最新的保存状态继续
  • On stop: the script quits & saves its current state.
  • On resume: the script starts, but continues from the latest saved state

我将使用 pickle signal 模块实现它.

I'm going to implement it using the pickle and the signal modules.

我将很高兴听到如何以pythonic方式进行操作.

I'll be glad to hear how to do it in pythonic way.

谢谢!

推荐答案

以下内容很简单,希望可以对您有所帮助:

Here is something simple that hopefully can help you:

import time
import pickle


REGISTRY = None


def main(start=0):
    """Do some heavy work ..."""

    global REGISTRY

    a = start
    while 1:
        time.sleep(1)
        a += 1
        print a
        REGISTRY = pickle.dumps(a)


if __name__ == '__main__':
    print "To stop the script execution type CTRL-C"
    while 1:
       start = pickle.loads(REGISTRY) if REGISTRY else 0
        try:
            main(start=start)
        except KeyboardInterrupt:
            resume = raw_input('If you want to continue type the letter c:')
            if resume != 'c':
                break

运行示例:

$ python test.py
To stop the script execution type CTRL-C
1
2
3
^CIf you want to continue type the letter c:c
4
5
6
7
8
9
^CIf you want to continue type the letter c:
$ python test.py

这篇关于如何“停止"和“恢复"长时间运行Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆