<p>你不能腌制发电机。阅读更多关于它的信息<a href="https://bugs.python.org/issue1092962" rel="nofollow noreferrer">here</a></p>
<p>有一篇博文对此做了更详细的解释。引用其中的一段话:</p>
<blockquote>
<p>Let’s ignore that problem for a moment and look what we would need to do to pickle a generator. Since a generator is essentially a souped-up function, we would need to save its bytecode, which is not guarantee to be backward-compatible between Python’s versions, and its frame, which holds the state of the generator such as local variables, closures and the instruction pointer. And this latter is rather cumbersome to accomplish, since it basically requires to make the whole interpreter picklable. So, any support for pickling generators would require a large number of changes to CPython’s core.</p>
</blockquote>
<blockquote>
<p>Now if an object unsupported by pickle (e.g., a file handle, a socket, a database connection, etc) occurs in the local variables of a generator, then that generator could not be pickled automatically, regardless of any pickle support for generators we might implement. So in that case, you would still need to provide custom <strong>getstate</strong> and <strong>setstate</strong> methods. This problem renders any pickling support for generators rather limited.</p>
</blockquote>
<p>他还提出了一个解决方案,使用简单的迭代器</p>
<blockquote>
<p>the best solution to this problem to the rewrite the generators as simple iterators (i.e., one with a <code>__next__</code> method). Iterators are easy and efficient space-wise to pickle because their state is explicit. You would still need to handle objects representing some external state explicitly however; you cannot get around this.</p>
</blockquote>
<p>另一个提供的<a href="https://web.archive.org/web/20160112050840/http://metaoptimize.com/blog/2009/12/22/why-cant-you-pickle-generators-in-python-workaround-pattern-for-saving-training-state/" rel="nofollow noreferrer">solution</a>(我没有尝试过)表明了这一点</p>
<ol>
<li><p>将生成器转换为一个类,其中生成器代码是<code>__iter__</code>方法</p>
</li>
<li><p>将<code>__getstate__</code>和<code>__setstate__</code>方法添加到类中,以处理拾取问题。请记住,不能对文件对象进行pickle。因此<code>__setstate__</code>必须根据需要重新打开文件</p>
</li>
</ol>