python - 是否可以在 python 中 pickle itertools.product?

标签 python pickle python-itertools resume

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

最佳答案

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

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

关于python - 是否可以在 python 中 pickle itertools.product?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831690/

相关文章:

python - Ubuntu, fatal error : Python. h : No such file or directory #include <Python. h>

Python 将模块名称视为 'NoneType'

python - 从 Jupyter notebook 文件夹打开多个 pickle 文件不起作用

python - 如何从 itertools groupby for 语句中提取摘要列表

python - 根据单个列表的排序对python中的多个列表进行排序

python - MaxProductOfThree 如何提高性能

python - python中的dir函数

python - 如何绘制颜色 QtGui.QPainterPath.addRect()?

python - 带有 C 指针的 Pickle Cython 类

python - 更改 Pickle 文件的内容