我可以在内存中腌制Python对象而不是物理文件吗?

时间:2017-11-15 12:12:35

标签: python serialization pickle

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

甚至可能吗?

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参数'file'(pos 1)not found

1 个答案:

答案 0 :(得分:5)

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

  

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

您可以创建自己的类来存储pickle数据,而不是使用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