Debian Codegraph @

Doc/library/plistlib.rst

raw
1 :mod:`!plistlib` --- Generate and parse Apple ``.plist`` files
2 ==============================================================
3
4 .. module:: plistlib
5 :synopsis: Generate and parse Apple plist files.
6
7 .. moduleauthor:: Jack Jansen
8 .. sectionauthor:: Georg Brandl <[email protected]>
9 .. (harvested from docstrings in the original file)
10
11 **Source code:** :source:`Lib/plistlib.py`
12
13 .. index::
14 pair: plist; file
15 single: property list
16
17 --------------
18
19 This module provides an interface for reading and writing the "property list"
20 files used by Apple, primarily on macOS and iOS. This module supports both binary
21 and XML plist files.
22
23 The property list (``.plist``) file format is a simple serialization supporting
24 basic object types, like dictionaries, lists, numbers and strings. Usually the
25 top level object is a dictionary.
26
27 To write out and to parse a plist file, use the :func:`dump` and
28 :func:`load` functions.
29
30 To work with plist data in bytes or string objects, use :func:`dumps`
31 and :func:`loads`.
32
33 Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
34 (but only with string keys), :class:`bytes`, :class:`bytearray`
35 or :class:`datetime.datetime` objects.
36
37 .. versionchanged:: 3.4
38 New API, old API deprecated. Support for binary format plists added.
39
40 .. versionchanged:: 3.8
41 Support added for reading and writing :class:`UID` tokens in binary plists as used
42 by NSKeyedArchiver and NSKeyedUnarchiver.
43
44 .. versionchanged:: 3.9
45 Old API removed.
46
47 .. seealso::
48
49 `PList manual page <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/PropertyLists/>`_
50 Apple's documentation of the file format.
51
52
53 This module defines the following functions:
54
55 .. function:: load(fp, *, fmt=None, dict_type=dict, aware_datetime=False)
56
57 Read a plist file. *fp* should be a readable and binary file object.
58 Return the unpacked root object (which usually is a
59 dictionary).
60
61 The *fmt* is the format of the file and the following values are valid:
62
63 * :data:`None`: Autodetect the file format
64
65 * :data:`FMT_XML`: XML file format
66
67 * :data:`FMT_BINARY`: Binary plist format
68
69 The *dict_type* is the type used for dictionaries that are read from the
70 plist file.
71
72 When *aware_datetime* is true, fields with type ``datetime.datetime`` will
73 be created as :ref:`aware object <datetime-naive-aware>`, with
74 :attr:`!tzinfo` as :const:`datetime.UTC`.
75
76 XML data for the :data:`FMT_XML` format is parsed using the Expat parser
77 from :mod:`xml.parsers.expat` -- see its documentation for possible
78 exceptions on ill-formed XML. Unknown elements will simply be ignored
79 by the plist parser.
80
81 The parser raises :exc:`InvalidFileException` when the file cannot be parsed.
82
83 .. versionadded:: 3.4
84
85 .. versionchanged:: 3.13
86 The keyword-only parameter *aware_datetime* has been added.
87
88
89 .. function:: loads(data, *, fmt=None, dict_type=dict, aware_datetime=False)
90
91 Load a plist from a bytes or string object. See :func:`load` for an
92 explanation of the keyword arguments.
93
94 .. versionadded:: 3.4
95
96 .. versionchanged:: 3.13
97 *data* can be a string when *fmt* equals :data:`FMT_XML`.
98
99 .. function:: dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)
100
101 Write *value* to a plist file. *fp* should be a writable, binary
102 file object.
103
104 The *fmt* argument specifies the format of the plist file and can be
105 one of the following values:
106
107 * :data:`FMT_XML`: XML formatted plist file
108
109 * :data:`FMT_BINARY`: Binary formatted plist file
110
111 When *sort_keys* is true (the default) the keys for dictionaries will be
112 written to the plist in sorted order, otherwise they will be written in
113 the iteration order of the dictionary.
114
115 When *skipkeys* is false (the default) the function raises :exc:`TypeError`
116 when a key of a dictionary is not a string, otherwise such keys are skipped.
117
118 When *aware_datetime* is true and any field with type ``datetime.datetime``
119 is set as an :ref:`aware object <datetime-naive-aware>`, it will convert to
120 UTC timezone before writing it.
121
122 A :exc:`TypeError` will be raised if the object is of an unsupported type or
123 a container that contains objects of unsupported types.
124
125 An :exc:`OverflowError` will be raised for integer values that cannot
126 be represented in (binary) plist files.
127
128 .. versionadded:: 3.4
129
130 .. versionchanged:: 3.13
131 The keyword-only parameter *aware_datetime* has been added.
132
133
134 .. function:: dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False, aware_datetime=False)
135
136 Return *value* as a plist-formatted bytes object. See
137 the documentation for :func:`dump` for an explanation of the keyword
138 arguments of this function.
139
140 .. versionadded:: 3.4
141
142
143 The following classes are available:
144
145 .. class:: UID(data)
146
147 Wraps an :class:`int`. This is used when reading or writing NSKeyedArchiver
148 encoded data, which contains UID (see PList manual).
149
150 .. attribute:: data
151
152 Int value of the UID. It must be in the range ``0 <= data < 2**64``.
153
154 .. versionadded:: 3.8
155
156
157 The following constants are available:
158
159 .. data:: FMT_XML
160
161 The XML format for plist files.
162
163 .. versionadded:: 3.4
164
165
166 .. data:: FMT_BINARY
167
168 The binary format for plist files
169
170 .. versionadded:: 3.4
171
172
173 The module defines the following exceptions:
174
175 .. exception:: InvalidFileException
176
177 Raised when a file cannot be parsed.
178
179 .. versionadded:: 3.4
180
181
182 Examples
183 --------
184
185 Generating a plist::
186
187 import datetime as dt
188 import plistlib
189
190 pl = dict(
191 aString = "Doodah",
192 aList = ["A", "B", 12, 32.1, [1, 2, 3]],
193 aFloat = 0.1,
194 anInt = 728,
195 aDict = dict(
196 anotherString = "<hello & hi there!>",
197 aThirdString = "M\xe4ssig, Ma\xdf",
198 aTrueValue = True,
199 aFalseValue = False,
200 ),
201 someData = b"<binary gunk>",
202 someMoreData = b"<lots of binary gunk>" * 10,
203 aDate = dt.datetime.now()
204 )
205 print(plistlib.dumps(pl).decode())
206
207 Parsing a plist::
208
209 import plistlib
210
211 plist = b"""<plist version="1.0">
212 <dict>
213 <key>foo</key>
214 <string>bar</string>
215 </dict>
216 </plist>"""
217 pl = plistlib.loads(plist)
218 print(pl["foo"])