我想保存以下状态itertools.product()我的程序退出后。可以用酸洗来做到这一点吗?我计划做的是生成排列,如果该过程被中断(键盘中断),我可以在下次运行程序时恢复该过程。
def trywith(itr):
try:
for word in itr:
time.sleep(1)
print("".join(word))
except KeyboardInterrupt:
f=open("/root/pickle.dat","wb")
pickle.dump((itr),f)
f.close()
if os.path.exists("/root/pickle.dat"):
f=open("/root/pickle.dat","rb")
itr=pickle.load(f)
trywith(itr)
else:
try:
itr=itertools.product('abcd',repeat=3)
for word in itr:
time.sleep(1)
print("".join(word))
except KeyboardInterrupt:
f=open("/root/pickle.dat","wb")
pickle.dump((itr),f)
f.close()
在Python 2中,没有对各种pickle的支持迭代工具.
然而,在Python 3中,添加了pickling支持,因此itertools.product()迭代器应该可以正常腌制:
>>> import pickle
>>> import itertools
>>> it = itertools.product(range(2), repeat=3)
>>> next(it)
(0, 0, 0)
>>> next(it)
(0, 0, 1)
>>> next(it)
(0, 1, 0)
>>> p = pickle.dumps(it)
>>> del it
>>> it = pickle.loads(p)
>>> next(it)
(0, 1, 1)
>>> next(it)
(1, 0, 0)
>>> next(it)
(1, 0, 1)
>>> next(it)
(1, 1, 0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)