我想在程序退出后保存 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()
也许最简单的事情就是保存将生成的下一组。然后,将来的运行可以重建以该组开头的新产品实例:
def restart_product_at(start_group, *pools):
n = 0 # Position of the start_group
for element, pool in zip(start_group, pools):
n *= len(pool)
n += pool.index(element)
p = product(*pools) # New fresh iterator
next(islice(p, n, n), None) # Advance n steps ahead
return p
例如:
>>> p = restart_product_at(('c', 'e', 'm'), 'abcd', 'efg', 'hijklm')
>>> next(p)
('c', 'e', 'm')
>>> next(p)
('c', 'f', 'h')
>>> next(p)
('c', 'f', 'i')