【问题标题】:How to "stop" and "resume" long time running Python script?如何“停止”和“恢复”长时间运行的 Python 脚本?
【发布时间】:2011-06-09 21:12:25
【问题描述】:

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

  • 停止:脚本退出并保存其当前状态。
  • 恢复:脚本启动,但从最新保存的状态继续

我将使用 picklesignal 模块来实现它。

我很高兴听到如何以 Python 方式进行操作。

谢谢!

【问题讨论】:

  • 您可能需要一些外部控制,例如计划任务(或 linux 中的 cron 作业)。另外,在程序停止时,将一些状态信息写入磁盘上的特定文件,以便您的程序知道重新启动时该做什么
  • 如果在 *nix 系统上,您可以使用标准的 SIGSTOP 和 SIGCONT 信号,尽管进程将保留在(虚拟)内存中直到继续。

标签: python pickle


【解决方案1】:

这里有一些简单的东西,希望可以帮助你:

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

【讨论】:

  • OP 想要处理一些文本文件。因此,全局变量中应该有文件句柄。 pickle 无法序列化文件句柄。因此,一般来说,您的答案不应该起作用……尤其是对于 OP 想要的。
【解决方案2】:

如果您要读取大文件,只需使用文件句柄,一次读取一行,根据需要处理每一行。如果你想保存 python 会话,那么只需使用dill.dump_session——它将保存所有现有对象。其他答案将失败,因为 pickle 无法腌制文件句柄。但是,dill 可以序列化几乎所有 python 对象——包括文件句柄。

Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> f = open('bigfile1.dat', 'r')
>>> data = f.readline()  
>>> 
>>> dill.dump_session('session.pkl')
>>> 

然后退出 python 会话,然后重新启动。当您load_session 时,您会加载在调用dump_session 时存在的所有对象。

dude@hilbert>$ python
Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('session.pkl')
>>> len(data)
9
>>> data += f.readline()
>>> f.close()
>>> 

就这么简单。

在此处获取dillhttps://github.com/uqfoundation

【讨论】:

    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多