简体   繁体   English

Pickle Python序列化

[英]Pickle Python Serialization

In layman's terms, what is "Serialization", and why do I need it? 用外行的话来说,什么是“序列化”,为什么我需要它? I read the Wikipedia entry, but still don't understand it. 我阅读了Wikipedia条目,但仍然不明白。 Why do I need to convert data into a sequence of bits to store it in a file? 为什么需要将数据转换为位序列以将其存储在文件中? I am specifically concerned with using Python's pickle module to do serialization. 我特别关心使用Python的pickle模块进行序列化。

Thanks for the time! 感谢您的时间!

You can save the state of a programm (of specific objects). 您可以保存(特定对象的)编程状态。 Imagine you have a program which runs for many hours or even days. 假设您有一个可以运行数小时甚至数天的程序。 Using pickle you can save the state of the calculation, kill the programm and resume the calculation later if you want to. 使用pickle,您可以保存计算状态,终止程序并在以后恢复计算。

You could even email the saved objects to other people, who than can resume the calculation or view your results. 您甚至可以将保存的对象通过电子邮件发送给其他人,然后其他人可以继续计算或查看结果。

I sometimes pickle userpreferences or (in a quiz) what questions where asked the last time and what answers were given. 有时我会挑剔用户的偏好,或者(一次测验)对上一次问什么问题以及给出什么答案感到厌烦。

Let me try to explain using some examples... 让我尝试用一​​些例子来解释...

You need to pass a dictionary to some other python process that runs out of your python environment (maybe some other project or on some other machine)... 您需要将字典传递给不在python环境中使用的其他python进程(可能是其他项目或在其他计算机上)...

somelist = {1:1,2:2,3:3}

How can you pass this dictionary to that process? 您如何将该字典传递给该过程? You cannot convert it to string, even if you did, you cannot convert it back to its original form... 您无法将其转换为字符串,即使这样做也无法将其转换回其原始形式...

If you pickle this dictionary it will give you 如果您腌这本字典,它将给您

dumps({1: 1, 2: 2, 3: 3})
'(dp1\nI1\nI1\nsI2\nI2\nsI3\nI3\ns.'

which has a string-like structure... So you can send this via post, or something else... and the receiver can unpickle it to obtain the original object... 它具有类似字符串的结构...因此您可以通过邮寄或其他方式发送此消息...接收者可以将其解开以获取原始对象...

loads('(dp1\nI1\nI1\nsI2\nI2\nsI3\nI3\ns.')
{1: 1, 2: 2, 3: 3}

A program that produces some statistics, but not too much of it so that using DB is overkill. 一个程序会产生一些统计信息,但不会太多,因此使用DB是过大的。

For example, benchmarking a program to choose the best algorithm. 例如,对程序进行基准测试以选择最佳算法。

Upon completion it draws a graph. 完成后会绘制一个图形。 Now you might not like the way the graph is drawn. 现在您可能不喜欢图形的绘制方式。 You pickle the results, then unpickle in another script (perhaps after a couple of subsequent benchmark runs) and fine-tune the visualization as you wish. 您对结果进行腌制,然后在另一个脚本中进行腌制(可能在运行了几次后续基准测试之后),然后根据需要微调可视化效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM