【问题标题】:Can I pickle Python objects in memory instead of a physical file? [duplicate]我可以在内存中腌制 Python 对象而不是物理文件吗? [复制]
【发布时间】:2017-11-15 12:12:35
【问题描述】:

我在 Python 中看到并编写了用于腌制对象的代码。但它们都创建物理文件来包含数据。我希望我将数据写入内存并读取它并腌制它并传输它。

有可能吗?

from PIL import ImageGrab
import io
import codecs
import pickle


# Model class to send Process Data to the server
class ProcessData:
 process_id = 0
 project_id = 0
 task_id = 0
 start_time = 0
 end_time = 0
 user_id = 0
 weekend_id = 0

# Model class to send image data to the server
class ProcessScreen:
 process_id = 0
 image_data = bytearray()


image_name = "Dharmindar_screen.jpg"
ImageGrab.grab().save(image_name,"JPEG")

image_data = None
with codecs.open(image_name,'rb') as image_file:
 image_data = image_file.read()



serialized_process_data = io.BytesIO()

process_data = ProcessData()
process_data.process_id = 1
process_data.project_id = 2
process_data.task_id = 3
process_data.user_id = 4
process_data.weekend_id = 5
process_data.start_time = 676876
process_data.end_time = 787987

process_screen = ProcessScreen()
process_screen.process_id = process_data.process_id
process_screen.image_data = image_data


prepared_process_data = (process_data, process_screen)

process_data_serializer = pickle.Pickler()
process_data_serializer(serialized_process_data).dump(prepared_process_data)

print('Data serialized.')


if process_data_serializer is not None:
    d = process_data_serializer.getvalue()
    deserialized_data = None
    with open(d, 'rb') as serialized_data_file:
        process_deserializer = pickle.Unpickler(serialized_data_file)
        deserialized_data = process_deserializer.load()
else:
    print('Empty')

上面的代码抛出 TypeError: Required argument 'file' (pos 1) not found

【问题讨论】:

  • 你的意思是写到内存吗?如果您想将对象发送到其他 Python 代码,您可以简单地将其作为参数传递,您想要完成什么?
  • 只是我愿意通过 Socket 将我的数据发送到服务器。为此,我需要腌制物体。但是为此,我已经看过每个代码,他们说首先将对象以字节的形式写入文件,然后再次从该文件中检索。我想在内存中完成,而不是物理写入文件。
  • 你可以使用 StringIO 对象,它提供缓冲区实例,但正如 Shayn 所说,你应该真正解释一下你正在尝试做什么。
  • 使用pickle.dumps?
  • 不是你的问题的答案,但为什么不考虑使用像 GRPC 这样的东西,从长远来看,这可能会更易于维护 thttps://grpc.io/docs/tutorials/basic/python .html

标签: python serialization pickle


【解决方案1】:

你传递给pickle.dump的File对象只需要一个write方法,见https://docs.python.org/2/library/pickle.html#pickle.dump

file 必须有一个接受单个字符串参数的 write() 方法。因此它可以是为写入而打开的文件对象、StringIO 对象或任何其他满足此接口的自定义对象。

您甚至可以创建自己的类来存储腌制数据,而不是使用 StringIO 对象,例如

class MyFile(object):
    def __init__(self):
        self.data = []
    def write(self, stuff):
        self.data.append(stuff)

然后只是腌制到这个类的一个实例:

class ExampleClass(object):
    def __init__(self, x):
        self.data = x  
a = ExampleClass(123)
f = MyFile()
pickle.dump(a, f)

另一个选择是,正如@rawing 所建议的,使用pickle.dumps,它将直接返回一个您可以使用的字符串,比较here

【讨论】:

  • 你的方法绝对有效。但我正在寻找一些简单的东西,@Rawing 对这个问题发表了评论,并建议我应该使用 pickle.dumps 而不是 pickle .dump ,这很容易做到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
相关资源
最近更新 更多