如何"停止"和"恢复"长时间运行Python脚本?

Val*_*ine 8 python pickle

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

  • 车站:脚本退出和保存其当前状态.
  • 简历:剧本开始,但是从最新的保存状态持续

我将使用pickle信号模块来实现它.

我很高兴听到如何用pythonic方式做到这一点.

谢谢!

mou*_*uad 4

这是一些简单的事情,希望可以帮助你:

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
Run Code Online (Sandbox Code Playgroud)

运行示例:

$ 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
Run Code Online (Sandbox Code Playgroud)