0

尝试腌制 InteractiveInterpreter 的实例会导致以下错误


  File "", line 1, in 
  File "/usr/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 725, in save_inst
    save(stuff)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle ellipsis objects

据我所知,这很奇怪 InteractiveInterpreter 不是 Ellipsis 对象。有什么理由吗?还有其他方法可以腌制 InteractiveInterpreter 对象吗?

4

1 回答 1

1

由于某种原因Ellipsis不能在腌料机中腌制。但是您可以使用persistent id功能来实现这一点。

首先,你应该使用and对象而不是pickle.dumpand 。pickle.loadPicklerUnpickler

其次,您必须定义两个函数 - 第一个将获取一个对象并返回其 id(或None用于常规酸洗),第二个将在 unpickling 时将此 id 转换为对象。

工作示例:

import cPickle as pickle

def dump_ellipsis(obj):
    if obj is Ellipsis:
        return "Ellipsis"

def load_ellipsis(persid):
    if persid == "Ellipsis":
        return Ellipsis


storage = open("tmp.pkl", "w")

pickler = pickle.Pickler(storage)

pickler.persistent_id = dump_ellipsis

pickler.dump(Ellipsis)

storage.close()

storage = open("tmp.pkl")

unpickler = pickle.Unpickler(storage)

unpickler.persistent_load = load_ellipsis

print unpickler.load()
于 2012-11-06T18:37:23.830 回答