yieldした途中の状態をファイルに保存とかって出来ますか
要はこういう事ができればいいかなぁと思うのですが。
$ yield_serial.py
2
$ yield_serial.py
3
次のコードだとyieldした位置?が記憶されなくてNG。
import cPickle as pickle class YieldSerial(object): def __init__(self): self.a = 1 def script(self): self.a = 2 yield self.a self.a = 3 yield self.a def write_dat(c): try: f = open("yield_serial.dat", "w") pickle.dump(c,f) f.close() except IOError: print "IOError" def read_dat(): try: f = open("yield_serial.dat", "r") c = pickle.load(f) f.close() except IOError: raise IOError return c try: c = read_dat() except IOError: print "initialize YieldSerial" c = YieldSerial() for i in c.script(): print i write_dat(c) break
$ yield_serial.py
2
$ yield_serial.py
2
generatorを保存すればいいかと思ったらgenerator pickleできない・・
try: g = read_dat() except IOError: print "initialize YieldSerial" g = YieldSerial().script() print g.next() write_dat(g)
generator_tools使ったら、なんかwarning出るけど行けた。
http://taichino.com/tag/generator_tools
from generator_tools import dumps, loads class YieldSerial(object): def __init__(self): self.a = 1 def script(self): self.a = 2 yield self.a self.a = 3 yield self.a def write_dat(c): try: f = open("yield_serial.dat", "w") f.write(c) f.close() except IOError: print "IOError" def read_dat(): try: f = open("yield_serial.dat", "r") c = f.read() f.close() except IOError: raise IOError return c try: g = loads(read_dat()) except IOError: print "initialize YieldSerial" g = YieldSerial().script() print g.next() write_dat(dumps(g))
$ python yield_serial.py
initialize YieldSerial
2
$ python yield_serial.py
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/generator_tools-0.3.6-py2.6.egg/generator_tools/copygenerators.py:182: DeprecationWarning: object.__init__() takes no parameters
int.__init__(self, op)
3