Is it possible to pickle itertools.product in python?

僤鯓⒐⒋嵵緔 提交于 2019-12-23 22:20:30

问题


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()

回答1:


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

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)


来源:https://stackoverflow.com/questions/26831690/is-it-possible-to-pickle-itertools-product-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!