python - cPickle - 忽略它无法序列化的内容而不是引发异常

标签 python pickle

我正在使用 cPickle 序列化用于日志记录的数据。

我希望能够将我想要的任何东西放入对象中,然后将其序列化。通常这对 cPickle 没问题,但遇到了一个问题,我想序列化的对象之一包含一个函数。这导致 cPickle 引发异常。

我宁愿 cPickle 只是跳过它无法处理的东西,而不是导致整个过程崩溃。

实现这一目标的好方法是什么?

最佳答案

我假设您正在寻找一个尽力而为的解决方案,如果未 pickle 的结果无法正常运行,您也可以接受。

对于您的特定用例,您可能需要 register a pickle handler对于函数对象。只需使其成为一个足以满足您最大努力目的的虚拟处理程序。为函数创建一个处理程序是可能的,这很棘手。为避免影响其他 pickle 代码,您可能希望在退出日志记录代码时注销处理程序。

这是一个例子(没有任何注销):

import cPickle
import copy_reg
from types import FunctionType

# data to pickle: note that o['x'] is a lambda and they
# aren't natively picklable (at this time)
o = {'x': lambda x: x, 'y': 1}

# shows that o is not natively picklable (because of
# o['x'])
try:
    cPickle.dumps(o)
except TypeError:
    print "not natively picklable"
else:
    print "was pickled natively"

# create a mechanisms to turn unpickable functions int
# stub objects (the string "STUB" in this case)
def stub_pickler(obj):
    return stub_unpickler, ()
def stub_unpickler():
    return "STUB"
copy_reg.pickle(
    FunctionType,
    stub_pickler, stub_unpickler)

# shows that o is now picklable but o['x'] is restored
# to the stub object instead of its original lambda
print cPickle.loads(cPickle.dumps(o))

它打印:

not natively picklable
{'y': 1, 'x': 'STUB'}

关于python - cPickle - 忽略它无法序列化的内容而不是引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306683/

相关文章:

python - 计算连通图

python - 根据列值和其他列更新 Pandas 单元格

python - 更新目录时运行 Python 脚本

python - Pandas : groupby function + rolling mean + reset index returning Nan

linux - pickle load 导致 supervisord 仅在我的 Azure VM 中重启

python - Python 中优雅降级的 pickle

python - 使用 cron 执行时,来自 Python 的一个系统命令不起作用

python - 引用被 Python 中的 pickling 弄乱了

pickle - _pickle.UnpicklingError : pickle data was truncated

python - 写入 Pickle 文件时出现 FileNotFoundError