Python pickle模块学习(超级详细)
pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。
pickle模块只能在python中使用,python中几乎所有的数据类型(列表,字典,集合,类等)都可以用pickle来序列化,
pickle序列化后的数据,可读性差,人一般无法识别。
------------------------------------------
pickle.dump(obj, file[, protocol])
序列化对象,并将结果数据流写入到文件对象中。参数protocol是序列化模式,默认值为0,表示以文本的形式序列化。protocol的值还可以是1或2,表示以二进制的形式序列化。
------------------------------------------
pickle.load(file)
反序列化对象。将文件中的数据解析为一个Python对象。
其中要注意的是,在load(file)的时候,要让python能够找到类的定义,否则会报错:
比如下面的例子
[python] view plain copy
如果不注释掉del Person的话,那么会报错如下:
意思就是当前模块找不到类的定义了。
--------------------------------------------------
clear_memo()
清空pickler的“备忘”。使用Pickler实例在序列化对象的时候,它会“记住”已经被序列化的对象引用,所以对同一对象多次调用dump(obj),pickler不会“傻傻”的去多次序列化。
看下面的例子:
[python] view plain copy
上面的代码运行如下:
如果不注释掉,则运行结果是第二个。如果注释掉,那么运行结果是第一个。
主要是因为,python的pickle如果不clear_memo,则不会多次去序列化对象。
原文链接:点击打开链接
持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象。通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识。另外,还会让您更深一步地了解Python 的对象序列化能力。 什么是持久性? 持久性的基本思想很简单。假定有一个 Python 程序,它可能是一个管理日常待办事项的程序,您希望在多次执行这个程序之间可以保存应用程序对象(待办事项)。换句话说,您希望将对象存储在磁盘上,便于以后检索。这就是持久性。要达到这个目的,有几种方法,每一种方法都有其优缺点。 例如,可以将对象数据存储在某种格式的文本文件中,譬如 CSV 文件。或者可以用关系数据库,譬如 Gadfly、MySQL、PostgreSQL 或者 DB2。这些文件格式和数据库都非常优秀,对于所有这些存储机制,Python 都有健壮的接口。 这些存储机制都有一个共同点:存储的数据是独立于对这些数据进行操作的对象和程序。这样做的好处是,数据可以作为共享的资源,供其它应用程序使用。缺点是,用这种方式,可以允许其它程序访问对象的数据,这违背了面向对象的封装性原则 — 即对象的数据只能通过这个对象自身的公共(public)接口来访问。 另外,对于某些应用程序,关系数据库方法可能不是很理想。尤其是,关系数据库不理解对象。相反,关系数据库会强行使用自己的类型系统和关系数据模型(表),每张表包含一组元组(行),每行包含具有固定数目的静态类型字段(列)。如果应用程序的对象模型不能够方便地转换到关系模型,那么在将对象映射到元组以及将元组映射回对象方面,会碰到一定难度。这种困难常被称为阻碍性不匹配(impedence-mismatch)问题。 对象持久性 如果希望透明地存储 Python 对象,而不丢失其身份和类型等信息,则需要某种形式的对象序列化:它是一个将任意复杂的对象转成对象的文本或二进制表示的过程。同样,必须能够将对象经过序列化后的形式恢复到原有的对象。在 Python 中,这种序列化过程称为 pickle,可以将对象 pickle 成字符串、磁盘上的文件或者任何类似于文件的对象,也可以将这些字符串、文件或任何类似于文件的对象 unpickle 成原来的对象。我们将在本文后面详细讨论 pickle。 假定您喜欢将任何事物都保存成对象,而且希望避免将对象转换成某种基于非对象存储的开销;那么 pickle 文件可以提供这些好处,但有时可能需要比这种简单的 pickle 文件更健壮以及更具有可伸缩性的事物。例如,只用 pickle 不能解决命名和查找 pickle 文件这样的问题,另外,它也不能支持并发地访问持久性对象。如果需要这些方面的功能,则要求助类似于 ZODB(针对 Python 的 Z 对象数据库)这类数据库。ZODB 是一个健壮的、多用户的和面向对象的数据库系统,它能够存储和管理任意复杂的 Python 对象,并支持事务操作和并发控制。(请参阅 参考资料,以下载 ZODB。)令人足够感兴趣的是,甚至 ZODB 也依靠 Python 的本机序列化能力,而且要有效地使用 ZODB,必须充分了解 pickle。 另一种令人感兴趣的解决持久性问题的方法是 Prevayler,它最初是用 Java 实现的(有关 Prevaylor 方面的developerWorks 文章,请参阅 参考资料)。最近,一群 Python 程序员将 Prevayler 移植到了 Python 上,另起名为 PyPerSyst,由 SourceForge 托管(有关至 PyPerSyst 项目的链接,请参阅 参考资料)。Prevayler/PyPerSyst 概念也是建立在 Java 和 Python 语言的本机序列化能力之上。PyPerSyst 将整个对象系统保存在内存中,并通过不时地将系统快照 pickle 到磁盘以及维护一个命令日志(通过此日志可以重新应用最新的快照)来提供灾难恢复。所以,尽管使用 PyPerSyst 的应用程序受到可用内存的限制,但好处是本机对象系统可以完全装入到内存中,因而速度极快,而且实现起来要比如 ZODB 这样的数据库简单,ZODB 允许对象的数目比同时在能内存中所保持的对象要多。 既然我们已经简要讨论了存储持久对象的各种方法,那么现在该详细探讨 pickle 过程了。虽然我们主要感兴趣的是探索以各种方式来保存 Python 对象,而不必将其转换成某种其它格式,但我们仍然还有一些需要关注的地方,譬如:如何有效地 pickle 和 unpickle 简单对象以及复杂对象,包括定制类的实例;如何维护对象的引用,包括循环引用和递归引用;以及如何处理类定义发生的变化,从而使用以前经过 pickle 的实例时不会发生问题。我们将在随后关于 Python 的 pickle 能力探讨中涉及所有这些问题。 一些经过 pickle 的 Python pickle 模块及其同类模块 cPickle 向 Python 提供了 pickle 支持。后者是用 C 编码的,它具有更好的性能,对于大多数应用程序,推荐使用该模块。我们将继续讨论 pickle ,但本文的示例实际是利用了 cPickle 。由于其中大多数示例要用 Python shell 来显示,所以先展示一下如何导入 cPickle ,并可以作为 pickle 来引用它: >>> import cPickle as pickle 现在已经导入了该模块,接下来让我们看一下 pickle 接口。 pickle 模块提供了以下函数对: dumps(object) 返回一个字符串,它包含一个 pickle 格式的对象; loads(string) 返回包含在 pickle 字符串中的对象; dump(object, file) 将对象写到文件,这个文件可以是实际的物理文件,但也可以是任何类似于文件的对象,这个对象具有 write() 方法,可以接受单个的字符串参数; load(file) 返回包含在 pickle 文件中的对象。 缺省情况下, dumps() 和 dump() 使用可打印的 ASCII 表示来创建 pickle。两者都有一个 final 参数(可选),如果为 True ,则该参数指定用更快以及更小的二进制表示来创建 pickle。 loads() 和 load() 函数自动检测 pickle 是二进制格式还是文本格式。 清单 1 显示了一个交互式会话,这里使用了刚才所描述的 dumps() 和 loads() 函数: 清单 1. dumps() 和 loads() 的演示- >>> t1
- ('this is a string', 42, [1, 2, 3], None)
- >>> p1 = pickle.dumps(t1)
- >>> p1
- "(S'this is a string'/nI42/n(lp1/nI1/naI2/naI3/naNtp2/n."
- >>> print p1
- (S'this is a string'
- I42
- (lp1
- I1
- aI2
- aI3
- aNtp2
- .
- >>> t2 = pickle.loads(p1)
- >>> t2
- ('this is a string', 42, [1, 2, 3], None)
- >>> p2 = pickle.dumps(t1, True)
- >>> p2
- '(U/x10this is a stringK*]q/x01(K/x01K/x02K/x03eNtq/x02.'
- >>> t3 = pickle.loads(p2)
- >>> t3
- ('this is a string', 42, [1, 2, 3], None)
原文地址: 点击打开链接
19.4. Pickled Objects
19.4. Pickle对象
Probably the biggest limitation of DBM keyed files is in what they can store: data stored under a key must be a simple text string. If you want to store Python objects in a DBM file, you can sometimes manually convert them to and from strings on writes and reads (e.g., with str and eval calls), but this takes you only so far. For arbitrarily complex Python objects such as class instances and nested data structures, you need something more. Class instance objects, for example, cannot be later re-created from their standard string representations. Custom to-string conversions are error prone and not general.
DBM 键控文件(DBM keyed file)最大的限制也许在于他们可以存储的东西:一个键值下存储的数据必须是个简单文本字符串。如果您想要在DBM文件中储存Python对象,有时您 可以在读写的时候,手动进行与字符串的转换(例如,用str和eval调用),但只能做到这样。对任意复杂的Python对象,如类实例和嵌套的数据结 构,您需要更多的东西。例如,类实例对象以后无法从其标准字符串表达(string representation)重建。自定义的到字符串的转换容易出错,并且不通用。
The Python pickle module, a standard part of the Python system, provides the conversion step needed. It converts nearly arbitrary Python in-memory objects to and from a single linear string format, suitable for storing in flat files, shipping across network sockets between trusted sources, and so on. This conversion from object to string is often called serializationarbitrary data structures in memory are mapped to a serial string form.
Python 系统的标准部件,pickle模块,提供了所需的转换步骤。它可以将几乎任意的Python内存对象,转换为单一线性的字符串格式,使之适于无格式文件存 储,或在可靠来源之间跨越网络套接口传输等等,并可反向转换。这种从对象到字符串的转换通常被称为序列化(serialization):将内存中的任意 数据结构映射为串行字符串形式。
The string representation used for objects is also sometimes referred to as a byte stream, due to its linear format. It retains all the content and references structure of the original in-memory object. When the object is later re-created from its byte string, it will be a new in-memory object identical in structure and value to the original, though located at a different memory address. The re-created object is effectively a copy of the original.
对象的字符串表达由于其线性的格式,有时也被称为字节流。它包含了原始内存中对象的所有内容和引用结构。当对象后来从其字节串重建时,内存中新建的对象与原对象具有相同的结构和值,但位于不同的内存地址。该重建对象实际上是原对象的复制。
Pickling works on almost any Python datatypenumbers, lists, dictionaries, class instances, nested structures, and moreand so is a general way to store data. Because pickles contain native Python objects, there is almost no database API to be found; the objects stored are processed with normal Python syntax when they are later retrieved.
Pickle可用于几乎所有的Python数据类型:数字、列表、字典、类实例、嵌套结构,等等,因此它是存储数据的通用方法。因为pickle包含的是Python本地对象,所以几乎没有数据库的API;对象存储与处理及后来的提取用的都是通常的Python语法。
19.4.1. Using Object Pickling
19.4.1. 使用对象pickle
Pickling may sound complicated the first time you encounter it, but the good news is that Python hides all the complexity of object-to-string conversion. In fact, the pickle module 's interfaces are incredibly simple to use. For example, to pickle an object into a serialized string, we can either make a pickler and call its methods or use convenience functions in the module to achieve the same effect:
第 一次听到pickle,可能觉得有点复杂,但好消息是,Python隐藏了所有从对象到字符串转换的复杂性。事实上,pickle模块的接口简单易用,简 直令人难以置信。例如,要pickle对象到一个序列化字符串,我们可以生成一个pickler,并调用其方法,或使用模块中的便捷函数来达到相同的效 果:
Make a new pickler for pickling to an open output file object file.
生成一个新的pickler,用来pickle到一个打开的输出文件对象file。
Write an object onto the pickler's file/stream.
写一个对象到pickler的文件/流。
Same as the last two calls combined: pickle an object onto an open file.
等同于上两个调用的组合:pickle对象到一个打开的文件。
Return the pickled representation of object as a character string.
返回一个字符串作为已pickle对象的表达。
Unpickling from a serialized string back to the original object is similarboth object and convenience function interfaces are available:
从一个序列化字符串unpickle回原始对象是类似的,可以用对象也可以用便捷函数接口:
Make an unpickler for unpickling from an open input file object file.
生成一个unpickler,用来从一个打开的文件对象file unpickle。
Read an object from the unpickler's file/stream.
从unpickler的文件/流读取一个对象。
Same as the last two calls combined: unpickle an object from an open file.
等同于上两个调用的组合:从一个打开的文件unpickle一个对象。
Read an object from a character string rather than a file.
从字符串读取一个对象,而不是从文件。
Pickler and Unpickler are exported classes. In all of the preceding cases, file is either an open file object or any object that implements the same attributes as file objects:
Pickler和Unpickler是导出类。在上述所有情况下,file是个已打开的文件对象,或者是实现了以下文件对象属性的任何对象:
Pickler calls the file's write method with a string argument.
Pickler会调用文件的write方法,参数是个字符串。
Unpickler calls the file's read method with a byte count, and readline without arguments.
Unpickler会调用文件的read方法,参数是字节数,以及readline,无参数。
Any object that provides these attributes can be passed in to the file parameters. In particular, file can be an instance of a Python class that provides the read/write methods (i.e., the expected file-like interface). This lets you map pickled streams to in-memory objects with classes, for arbitrary use. For instance, the StringIO standard library module discussed in Chapter 3 provides classes that map file calls to and from in-memory strings.
任 何提供这些属性的对象都可以作为file参数传入。特别是,file可以是一个提供了读/写方法的Python类实例(即预期的类似文件的接口)。这让您 可以用类映射pickle流到内存对象,并可任意使用。例如,第3章讨论的标准库模块StringIO提供的类,它们可映射文件调用到内存字符串或反之。
This hook also lets you ship Python objects across a network, by providing sockets wrapped to look like files in pickle calls at the sender, and unpickle calls at the receiver (see the sidebar "Making Sockets Look Like Files," in Chapter 13, for more details). In fact, for some, pickling Python objects across a trusted network serves as a simpler alternative to network transport protocols such as SOAP and XML-RPC; provided that Python is on both ends of the communication (pickled objects are represented with a Python-specific format, not with XML text).
该 挂钩也可以让您通过网络传输Python对象,只要封装套接口,使之看上去像发送端pickle调用中的文件,以及像接收端unpickle调用中的文件 (详见第13章侧栏“使套接口看上去像文件”)。事实上,对一些人来说,pickle Python对象并在一个值得信赖的网络上传输,是替代如SOAP和XML-RPC之类网络传输协议的一个简单方法;只要通信的两端都有Python(被 pickle的对象是用Python专有的格式表达的,而不是用XML文本)。
19.4.2. Picking in Action
19.4.2. Pickle实战
In more typical use, to pickle an object to a flat file, we just open the file in write mode and call the dump function:
典型的使用情况是,pickle对象到无格式文件,我们只需以写模式打开文件,并调用dump函数:
Notice the nesting in the object pickled herethe pickler handles arbitrary structures. To unpickle later in another session or program run, simply reopen the file and call load:
注意这个被pickle对象中的嵌套:pickler可以处理任意结构。然后,在另一个会话或程序中unpickle,只要重新打开该文件,并调用load:
The object you get back from unpickling has the same value and reference structure as the original, but it is located at a different address in memory. This is true whether the object is unpickled in the same or a future process. In Python-speak, the unpickled object is == but is not is:
unpickle所得的对象具有与原对象相同的值和引用结构,但它位于不同的内存地址。无论在同一进程或另一进程unpickle,都是这样。用Python的话来说,unpickle后的对象是“==”关系,但不是“is”关系:
To make this process simpler still, the module in Example 19-1 wraps pickling and unpickling calls in functions that also open the files where the serialized form of the object is stored.
为了让这一过程更简单,例19-1中的模块把pickle和unpickle调用封装在函数中,在函数中同时还打开文件,并将对象的序列化存储在该文件中。
Example 19-1. PP3E\Dbase\filepickle.py
切换行号显示
1 import pickle2 3 def saveDbase(filename, object):4 file = open(filename, 'w')5 pickle.dump(object, file) # pickle to file6 file.close( ) # any file-like object will do7 8 def loadDbase(filename):9 file = open(filename, 'r')10 object = pickle.load(file) # unpickle from file11 file.close( ) # re-creates object in memory12 return object
To store and fetch now, simply call these module functions; here they are in action managing a fairly complex structure with multiple references to the same nested objectthe nested list called L at first is stored only once in the file:
现在,存储和提取时只需调用这些模块函数;以下实例是个相当复杂的结构,具有对同一嵌套对象的多重引用,该嵌套列表,即第1个L,在文件中只会保存一次:
Besides built-in types like the lists, tuples, and dictionaries of the examples so far, class instances may also be pickled to file-like objects. This provides a natural way to associate behavior with stored data (class methods process instance attributes) and provides a simple migration path (class changes made in module files are automatically picked up by stored instances). Here's a brief interactive demonstration:
除 了内置的类型,如以上例子中的列表,元组和字典,类实例也可被pickle到类似文件的对象中。这提供了一个自然的方式来关联行为与存储的数据(类方法处 理实例的属性),并提供了一条简单的迁移路径(被存储的实例将自动获得模块文件中对类的更改)。以下是个简短的交互演示:
We'll explore how this works in more detail in conjunction with shelves later in this chapteras we'll see, although the pickle module can be used directly, it is also the underlying translation engine in both shelves and ZODB databases.
我们将与本章下面的shelve一起详细探讨这是如此工作的。我们将会看到,虽然pickle模块可直接使用,但它也是shelve和ZODB数据库的底层翻译引擎。
In fact, Python can pickle just about anything, except for:
事实上,Python可以pickle任何东西,除了:
Compiled code objects; functions and classes record just their names in pickles, to allow for later reimport and automatic acquisition of changes made in module files.
编译的代码对象;函数和类在pickle中只是记录了它们的名字,以便后来重新导入和自动获取模块文件中的更改。
Instances of classes that do not follow class importability rules (more on this at the end of the section "Shelve Files," later in this chapter).
不遵守类可导入规则(class importability rule)的类实例(本章后面“Shelve文件”一节的尾部有更多相关内容)。
Instances of some built-in and user-defined types that are coded in C or depend upon transient operating system states (e.g., open file objects cannot be pickled).
用C编码的或依赖于操作系统瞬态的一些内置的和用户定义类型的实例(例如,打开的文件对象无法pickle)。
A PicklingError is raised if an object cannot be pickled.
如果对象不能pickle,会引发PickleError。
19.4.3. Pickler Protocols and cPickle
19.4.3. Pickler协议和cPickle
In recent Python releases, the pickler introduced the notion of protocolsstorage formats for pickled data. Specify the desired protocol by passing an extra parameter to the pickling calls (but not to unpickling calls: the protocol is automatically determined from the pickled data):
在最近的Python版本中,pickler推出了协议的概念:pickle数据的保存格式。通过pickle调用时传入一个额外的参数,可指定所需的协议(但unpickle调用不需要:协议是自动从已pickle的数据确定的):
Pickled data may be created in either text or binary protocols. By default, the storage protocol is text (also known as protocol 0). In text mode, the files used to store pickled objects may be opened in text mode as in the earlier examples, and the pickled data is printable ASCII text, which can be read (it's essentially instructions for a stack machine).
Pickle 数据可以按文本协议或二进制协议产生。默认情况下,存储协议是文本协议(也称为0号协议)。在文本模式下,用来存储pickle对象的文件可以用文本模式 打开,如上述的例子,并且pickle的数据是可打印的ASCII文本,并且是可读的(这基本上是对堆栈机实现的指示)。
The alternative protocols (protocols 1 and 2) store the pickled data in binary format and require that files be opened in binary mode (e.g., rb, wb). Protocol 1 is the original binary format; protocol 2, added in Python 2.3, has improved support for pickling of new-style classes. Binary format is slightly more efficient, but it cannot be inspected. An older option to pickling calls, the bin argument, has been subsumed by using a pickling protocol higher than 0. The pickle module also provides a HIGHEST_PROTOCOL variable that can be passed in to automatically select the maximum value.
其 他协议(1号和2号协议 )以二进制格式存储pickle数据,并要求文件以二进制模式打开(例如:rb、wb)。1号协议是原始二进制格式;2号协议是Python 2.3增加的,它改善了对新型类pickle的支持。二进制格式效率更高一点,但它无法进行查看。旧的pickle调用有一个选项,即bin参数,现已被 归入使用大于0的协议。pickle模块还提供了一个HIGHEST_PROTOCOL变量,传入它可以自动选择最大的协议值。
One note: if you use the default text protocol, make sure you open pickle files in text mode later. On some platforms, opening text data in binary mode may cause unpickling errors due to line-end formats on Windows:
注意:如果您使用默认的文本协议,以后请务必以文本模式打开pickle文件。在一些平台上,因为Windows的行尾格式不同,以二进制模式打开文本数据可能会导致unpickle错误:
One way to sidestep this potential issue is to always use binary mode for your files, even for the text pickle protocol. Since you must open files in binary mode for the binary pickler protocols anyhow (higher than the default 0), this isn't a bad habit to get into:
回避这个潜在问题的方法之一是,总是使用二进制模式的文件,即使是用文本pickle协议。至少对于二进制pickler协议(高于默认0),您必须以二进制模式打开文件,所以这不是一个坏习惯:
Refer to Python's library manual for more information on the pickler. Also check out marshal, a module that serializes an object too, but can handle only simple object types. pickle is more general than marshal and is normally preferred.
请参考Python库手册,以了解更多pickler的信息。另外,请查阅marshal,它也是一个序列化对象的模块,但只能处理简单对象类型。pickle比marshal更通用,并通常是首选。
And while you are flipping (or clicking) through that manual, be sure to also see the entries for the cPickle modulea reimplementation of pickle coded in C for faster performance. You can explicitly import cPickle for a substantial speed boost; its chief limitation is that you cannot subclass its versions of Pickle and Unpickle because they are functions, not classes (this is not required by most programs). The pickle and cPickle modules use compatible data formats, so they may be used interchangeably.
而 当你翻看(或点击)Python手册时,请一定也要看看cPickle模块的条目,它是pickle的C语言实现,性能上更快。您可以显式导入 cPickle替代pickle,以大幅提升速度;其主要的限制是,你不能继承该版本的Pickle和Unpickle,因为它们是函数,而不是类(多数 程序并不要求它们是类)。pickle和cPickle模块使用兼容的数据格式,所以它们可以互换使用。
总结
以上是生活随笔为你收集整理的Python pickle模块学习(超级详细)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 计算机电路电子技术试题答案,数字电子技术
- 下一篇: 手机中的传感器及其应用场景