是否可以在python中腌制itertools.product? [英] Is it possible to pickle itertools.product in python?

查看:76
本文介绍了是否可以在python中腌制itertools.product?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在程序退出后保存 itertools.product()的状态.可以用酸洗吗?我打算做的是生成排列,如果进程被中断(KeyboardInterrupt),那么下次运行该程序时,我可以恢复该进程.

I would like to save the state of itertools.product() after my program quits. Is it possible to do this with pickling? What I am planning to do is to generate permutations and if the process is interrupted (KeyboardInterrupt), I can resume the process the next time I run the program.

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 的泡菜支持.

In Python 2, there is not pickle support for the various itertools.

但是,在Python 3中,增加了对酸洗的支持,因此 itertools.product()迭代器应该可以酸洗:

However, in Python 3, pickling support was added, so the itertools.product() iterator ought to pickle just fine:

>>> 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中腌制itertools.product?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆