2011-06-09 145 views
8

我寫了Python腳本,可以處理大量的大文本文件,並且可以運行很多時間。有時候,需要停止正在運行的腳本並稍後恢復。停止腳本的可能原因是程序崩潰,磁盤「空間不足」情況或許多其他情況,因此您必須執行該操作。我想爲腳本實現一種「停止/恢復」機制。如何「停止」和「恢復」長時間運行Python腳本?

  • 停止:腳本退出&保存其當前狀態。
  • 簡歷:劇本開始,但是從最新的保存狀態

繼續我要去使用泡菜信號模塊來實現它。

我很高興聽到如何以pythonic的方式做到這一點。

謝謝!

+0

您可能需要一些外部的控制,如計劃任務(或在Linux cron作業)。此外,在程序停止時,向磁盤上的特定文件寫入一些狀態信息,以便程序在重新啓動時知道該怎麼做 – inspectorG4dget 2011-06-09 21:37:11

+0

如果在* nix系統上,可以使用標準的SIGSTOP和SIGCONT信號,但該過程將保持在(虛擬)內存直到繼續。 – tzot 2011-06-10 09:25:02

回答

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 

運行的實例:

$ 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 
+1

OP想要處理多個文本文件。所以,全局變量中應該有文件句柄。 'pickle'不能序列化文件句柄。因此,一般來說,你的答案不應該起作用,特別是對於OP想要的東西。 – 2015-03-13 02:21:37

1

如果您正在尋找讀取大文件時,只使用一個文件句柄,並閱讀每行一行,根據需要處理每一行。如果您想保存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調用時存在的所有對象。

[email protected]>$ 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() 
>>> 

這樣簡單。

獲取dill這裏:https://github.com/uqfoundation