我想在程序退出后保存 itertools.product() 的状态。 pickle 可以做到这一点吗?我打算做的是生成排列,如果过程中断(KeyboardInterrupt),我可以在下次运行程序时恢复该过程。
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 中,没有对各种 itertools 的 pickle 支持。
但是,在 Python 3 中,添加了 pickling 支持,因此 itertools.product() 迭代器应该可以很好地 pickle:
>>> 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)
关于python - 是否可以在 python 中 pickle itertools.product?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831690/