signal
アプリケーションの終了時にハンドラーを使用してキャッチすることができます。これにより、終了する前に現在の状態を保存できます。次のスクリプトは、再起動時に継続する単純な数のカウントを示しています。
import signal, os, cPickle
class MyState:
def __init__(self):
self.count = 1
def stop_handler(signum, frame):
global running
running = False
signal.signal(signal.SIGINT, stop_handler)
running = True
state_filename = "state.txt"
if os.path.isfile(state_filename):
with open(state_filename, "rb") as f_state:
my_state = cPickle.load(f_state)
else:
my_state = MyState()
while running:
print my_state.count
my_state.count += 1
with open(state_filename, "wb") as f_state:
cPickle.dump(my_state, f_state)
ディスク書き込みの改善に関しては、Python 自体のファイル バッファリングを 1Mb 以上のサイズのバッファで増やしてみることができますopen('output.txt', 'w', 2**20)
。with
ハンドラーを使用すると、ファイルがフラッシュされて閉じられることも保証されます。