可以在python中pickle itertools.product吗?

可以在python中pickle itertools.product吗?,python,pickle,itertools,resume,Python,Pickle,Itertools,Resume,我想在程序退出后保存itertools.product()的状态。可以用酸洗来做吗?我计划做的是生成排列,如果进程被中断(键盘中断),我可以在下次运行程序时恢复进程 def trywith(itr): try: for word in itr: time.sleep(1) print("".join(word)) except KeyboardInterrupt: f=open("/roo

我想在程序退出后保存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()

在Python2中,没有对各种itertools的pickle支持

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

看一看Nice,但我一直在寻找一个更简单的解释,因为我还在探索python;没有比这更简单的解决方案了,我不认为。好的,谢谢jonrsharpe。我会看看我是否能试着理解和检查输入。