Pickle Python Serialization

▼魔方 西西 提交于 2019-12-30 12:06:23

问题


In layman's terms, what is "Serialization", and why do I need it? I read the Wikipedia entry, but still don't understand it. 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.

Thanks for the time!


回答1:


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.

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.




回答2:


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)...

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}



回答3:


A program that produces some statistics, but not too much of it so that using DB is overkill.

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.



来源:https://stackoverflow.com/questions/4106178/pickle-python-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!