Pickle.dump到变量 [英] Pickle.dump to variable

查看:88
本文介绍了Pickle.dump到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我想知道是否有解决此问题的方法:

I'm new in python and i wanted to know if there is a solution for this problem:

我知道这听起来很奇怪,但是我想将pickle.dump数据保存到变量中. 我开始认为我可以通过创建一个伪造的类来绕过它,而不是写一个文件,写一个变量:

I know that this may sound strange but i want to save the pickle.dump data into a variable. I begin to think that may i could bypass it by making a fake class to instead of writing in a file, writing in a variable:

class PickleDatatoVar(object):
def __init__(self):
    self.data = None
def write(self, data):
    self.data = data
def get(self):
    return self.data

然后:

pick = PickleDatatoVar()
pickle.dump(Int, pick)
var = pick.get()

什么都没有显示为错误,但是输出只是一个'.'

Nothing is presented as error, but the output is just a '.'

那么有解决方案,而不是将其保存在文件中保存为变量吗?

So is there a solution to instead of saving that in a file saving into a variable?

推荐答案

您正在寻找内存文件对象;在Python 2中 cStringIO.StringIO() ,对于Python 3

You are looking for an in-memory file object; in Python 2 that's cStringIO.StringIO(), for Python 3 io.BytesIO(); these act just like file objects and you can have pickle.dump() write to these.

但是,更简单的方法是使用 pickle.dumps() 直接转储到字符串对象.

However, the easier path would be to use pickle.dumps() to dump straight to a string object instead.

内幕pickle.dumps()为您执行的操作是创建一个内存文件对象,向其中写入泡菜数据,并为您检索字符串结果;参见源代码:

Under the hood, what pickle.dumps() does for you is create an in-memory file object, write the pickle data to it and retrieve the string result for you; see the source code:

def _dumps(obj, protocol=None, *, fix_imports=True):
    f = io.BytesIO()
    _Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
    res = f.getvalue()
    assert isinstance(res, bytes_types)
    return res

但是通过这种方式,您不必自己做额外的工作.

but this way you don't have to do that extra work yourself.

这篇关于Pickle.dump到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆