KeyboardInterruptされたら状態をファイルに退避して、再実行時に復帰する。
#!/usr/bin/python
import sys
import os
import time
import pickle
fname = 'serialized'
try:
f = open(fname, 'r')
counter = pickle.load(f)
f.close()
except:
counter = 0
pass
try:
while counter < 10:
print counter
counter += 1
time.sleep(1)
except KeyboardInterrupt:
print 'Got KeyboardInterrupt'
f = open(fname, 'w')
pickle.dump(counter, f)
f.close()
sys.exit()
try:
os.remove(fname)
except:
pass
実行結果:
[nori@nagato]~/Desktop/backgammon/bgonline% python int.py
0
1
Got KeyboardInterrupt
[nori@nagato]~/Desktop/backgammon/bgonline% python int.py
2
3
4
5
6
7
8
9
[nori@nagato]~/Desktop/backgammon/bgonline% python int.py
0
1
2
3
4
5
6
7
8
9
[nori@nagato]~/Desktop/backgammon/bgonline%
0 件のコメント:
コメントを投稿