Python 中 pickle 的常见用例 [英] Common use-cases for pickle in Python

查看:22
本文介绍了Python 中 pickle 的常见用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过 pickle 文档,但我没有了解泡菜的用处.

I've looked at the pickle documentation, but I don't understand where pickle is useful.

pickle 有哪些常见用例?

What are some common use-cases for pickle?

推荐答案

我遇到的一些用途:

1) 将程序的状态数据保存到磁盘,以便它可以在重新启动时从停止的地方继续(持久性)

1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence)

2) 在多核或分布式系统中通过 TCP 连接发送 python 数据(编组)

2) sending python data over a TCP connection in a multi-core or distributed system (marshalling)

3) 在数据库中存储 python 对象

3) storing python objects in a database

4) 将任意 Python 对象转换为字符串,以便将其用作字典键(例如用于缓存和记忆).

4) converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).

最后一个存在一些问题 - 两个相同的对象可能会被酸洗并导致不同的字符串 - 甚至同一个对象被酸洗两次也可能有不同的表示.这是因为泡菜可以包含引用计数信息.

There are some issues with the last one - two identical objects can be pickled and result in different strings - or even the same object pickled twice can have different representations. This is because the pickle can include reference count information.

为了强调@lunaryorn 的评论——你永远不应该从不受信任的来源解开一个字符串,因为精心制作的pickle 可以在你的系统上执行任意代码.例如,参见 https://blog.nelhage.com/2011/03/exploiting-pickle/

To emphasise @lunaryorn's comment - you should never unpickle a string from an untrusted source, since a carefully crafted pickle could execute arbitrary code on your system. For example see https://blog.nelhage.com/2011/03/exploiting-pickle/

这篇关于Python 中 pickle 的常见用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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