为什么我们不能挑选InteractiveInterpreter的实例?

时间:2012-11-06 17:06:01

标签: python serialization pickle

尝试pickle 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对象?

1 个答案:

答案 0 :(得分:1)

由于某种原因,Ellipsis无法在股票选择器中腌制。但您可以使用persistent id功能来实现此目的。

首先,您应使用pickle.dumppickle.load对象,而不是PicklerUnpickler

其次,你必须定义两个函数 - 首先是一个对象并返回它的id(或None进行常规的pickle),然后第二个将这个id转换为对象进行unpickling。

工作示例:

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