擅长:python、mysql、java
<p>您可以尝试使用<code>signal</code>处理程序在应用程序终止时捕获。这样可以在终止前保存当前状态。下面的脚本显示了在重新启动时继续进行的简单的数字计数。在</p>
<pre><code>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)
</code></pre>
<p>至于改进磁盘写入,您可以尝试使用1Mb或更大大小的缓冲区来增加Python自己的文件缓冲区,例如<code>open('output.txt', 'w', 2**20)</code>。使用<code>with</code>处理程序还应确保文件被刷新并关闭。在</p>