是否有可能在python中腌制itertools.product?

时间:2014-11-09 18:27:32

标签: python pickle itertools resume

我希望在程序退出后保存 itertools.product()的状态。酸洗可以做到这一点吗?我打算做的是生成排列,如果进程被中断(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()

1 个答案:

答案 0 :(得分:0)

在Python 2中,没有针对各种 itertools 的pickle支持。

但是,在Python 3中,添加了pickle支持,所以 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)