Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 1 | """plistlib.py -- a tool to generate and parse MacOSX .plist files. |
| 2 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 3 | The PropertList (.plist) file format is a simple XML pickle supporting |
| 4 | basic object types, like dictionaries, lists, numbers and strings. |
| 5 | Usually the top level object is a dictionary. |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 6 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 7 | To write out a plist file, use the writePlist(rootObject, pathOrFile) |
| 8 | function. 'rootObject' is the top level object, 'pathOrFile' is a |
| 9 | filename or a (writable) file object. |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 10 | |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 11 | To parse a plist from a file, use the readPlist(pathOrFile) function, |
| 12 | with a file name or a (readable) file object as the only argument. It |
| 13 | returns the top level object (again, usually a dictionary). |
| 14 | |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 15 | To work with plist data in bytes objects, you can use readPlistFromBytes() |
| 16 | and writePlistToBytes(). |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 17 | |
| 18 | Values can be strings, integers, floats, booleans, tuples, lists, |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 19 | dictionaries, Data or datetime.datetime objects. String values (including |
| 20 | dictionary keys) may be unicode strings -- they will be written out as |
| 21 | UTF-8. |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 22 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 23 | The <data> plist type is supported through the Data class. This is a |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 24 | thin wrapper around a Python bytes object. |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 25 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 26 | Generate Plist example: |
| 27 | |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 28 | pl = dict( |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 29 | aString="Doodah", |
| 30 | aList=["A", "B", 12, 32.1, [1, 2, 3]], |
| 31 | aFloat = 0.1, |
| 32 | anInt = 728, |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 33 | aDict=dict( |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 34 | anotherString="<hello & hi there!>", |
| 35 | aUnicodeValue=u'M\xe4ssig, Ma\xdf', |
| 36 | aTrueValue=True, |
| 37 | aFalseValue=False, |
| 38 | ), |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 39 | someData = Data(b"<binary gunk>"), |
| 40 | someMoreData = Data(b"<lots of binary gunk>" * 10), |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 41 | aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 42 | ) |
| 43 | # unicode keys are possible, but a little awkward to use: |
| 44 | pl[u'\xc5benraa'] = "That was a unicode key." |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 45 | writePlist(pl, fileName) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 46 | |
| 47 | Parse Plist example: |
| 48 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 49 | pl = readPlist(pathOrFile) |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 50 | print pl["aKey"] |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 51 | """ |
| 52 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 53 | |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 54 | __all__ = [ |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 55 | "readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 56 | "readPlistFromResource", "writePlistToResource", |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 57 | "Plist", "Data", "Dict" |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 58 | ] |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 59 | # Note: the Plist and Dict classes have been deprecated. |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 60 | |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 61 | import binascii |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 62 | import datetime |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 63 | from io import BytesIO |
Just van Rossum | 26e811a | 2004-11-12 08:02:35 +0000 | [diff] [blame] | 64 | import re |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 65 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 66 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 67 | def readPlist(pathOrFile): |
| 68 | """Read a .plist file. 'pathOrFile' may either be a file name or a |
| 69 | (readable) file object. Return the unpacked root object (which |
| 70 | usually is a dictionary). |
| 71 | """ |
Collin Winter | b9678e7 | 2007-08-30 18:11:17 +0000 | [diff] [blame^] | 72 | didOpen = False |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 73 | if isinstance(pathOrFile, str): |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 74 | pathOrFile = open(pathOrFile, 'rb') |
Collin Winter | b9678e7 | 2007-08-30 18:11:17 +0000 | [diff] [blame^] | 75 | didOpen = True |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 76 | p = PlistParser() |
| 77 | rootObject = p.parse(pathOrFile) |
| 78 | if didOpen: |
| 79 | pathOrFile.close() |
| 80 | return rootObject |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 81 | |
| 82 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 83 | def writePlist(rootObject, pathOrFile): |
| 84 | """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a |
| 85 | file name or a (writable) file object. |
| 86 | """ |
Collin Winter | b9678e7 | 2007-08-30 18:11:17 +0000 | [diff] [blame^] | 87 | didOpen = False |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 88 | if isinstance(pathOrFile, str): |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 89 | pathOrFile = open(pathOrFile, 'wb') |
Collin Winter | b9678e7 | 2007-08-30 18:11:17 +0000 | [diff] [blame^] | 90 | didOpen = True |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 91 | writer = PlistWriter(pathOrFile) |
| 92 | writer.writeln("<plist version=\"1.0\">") |
| 93 | writer.writeValue(rootObject) |
| 94 | writer.writeln("</plist>") |
| 95 | if didOpen: |
| 96 | pathOrFile.close() |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 97 | |
| 98 | |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 99 | def readPlistFromBytes(data): |
| 100 | """Read a plist data from a bytes object. Return the root object. |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 101 | """ |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 102 | return readPlist(BytesIO(data)) |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 103 | |
| 104 | |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 105 | def writePlistToBytes(rootObject): |
| 106 | """Return 'rootObject' as a plist-formatted bytes object. |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 107 | """ |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 108 | f = BytesIO() |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 109 | writePlist(rootObject, f) |
| 110 | return f.getvalue() |
| 111 | |
| 112 | |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 113 | def readPlistFromResource(path, restype='plst', resid=0): |
| 114 | """Read plst resource from the resource fork of path. |
| 115 | """ |
| 116 | from Carbon.File import FSRef, FSGetResourceForkName |
| 117 | from Carbon.Files import fsRdPerm |
| 118 | from Carbon import Res |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 119 | fsRef = FSRef(path) |
| 120 | resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm) |
| 121 | Res.UseResFile(resNum) |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 122 | plistData = Res.Get1Resource(restype, resid).data |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 123 | Res.CloseResFile(resNum) |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 124 | return readPlistFromString(plistData) |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 125 | |
| 126 | |
| 127 | def writePlistToResource(rootObject, path, restype='plst', resid=0): |
| 128 | """Write 'rootObject' as a plst resource to the resource fork of path. |
| 129 | """ |
| 130 | from Carbon.File import FSRef, FSGetResourceForkName |
| 131 | from Carbon.Files import fsRdWrPerm |
| 132 | from Carbon import Res |
Just van Rossum | c6fdd1b | 2004-10-26 06:50:50 +0000 | [diff] [blame] | 133 | plistData = writePlistToString(rootObject) |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 134 | fsRef = FSRef(path) |
| 135 | resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm) |
| 136 | Res.UseResFile(resNum) |
| 137 | try: |
| 138 | Res.Get1Resource(restype, resid).RemoveResource() |
| 139 | except Res.Error: |
| 140 | pass |
| 141 | res = Res.Resource(plistData) |
| 142 | res.AddResource(restype, resid, '') |
| 143 | res.WriteResource() |
| 144 | Res.CloseResFile(resNum) |
| 145 | |
| 146 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 147 | class DumbXMLWriter: |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 148 | def __init__(self, file, indentLevel=0, indent="\t"): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 149 | self.file = file |
| 150 | self.stack = [] |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 151 | self.indentLevel = indentLevel |
| 152 | self.indent = indent |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 153 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 154 | def beginElement(self, element): |
| 155 | self.stack.append(element) |
| 156 | self.writeln("<%s>" % element) |
| 157 | self.indentLevel += 1 |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 158 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 159 | def endElement(self, element): |
| 160 | assert self.indentLevel > 0 |
| 161 | assert self.stack.pop() == element |
| 162 | self.indentLevel -= 1 |
| 163 | self.writeln("</%s>" % element) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 164 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 165 | def simpleElement(self, element, value=None): |
Just van Rossum | 87316ec | 2003-07-10 14:26:06 +0000 | [diff] [blame] | 166 | if value is not None: |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 167 | value = _escapeAndEncode(value) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 168 | self.writeln("<%s>%s</%s>" % (element, value, element)) |
| 169 | else: |
| 170 | self.writeln("<%s/>" % element) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 171 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 172 | def writeln(self, line): |
| 173 | if line: |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 174 | # plist has fixed encoding of utf-8 |
| 175 | if isinstance(line, str): |
| 176 | line = line.encode('utf-8') |
| 177 | self.file.write(self.indentLevel * self.indent) |
| 178 | self.file.write(line) |
Guido van Rossum | 6dab795 | 2007-08-27 17:25:39 +0000 | [diff] [blame] | 179 | self.file.write(b'\n') |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 180 | |
| 181 | |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 182 | # Contents should conform to a subset of ISO 8601 |
| 183 | # (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units may be omitted with |
| 184 | # a loss of precision) |
| 185 | _dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z") |
| 186 | |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 187 | def _dateFromString(s): |
| 188 | order = ('year', 'month', 'day', 'hour', 'minute', 'second') |
| 189 | gd = _dateParser.match(s).groupdict() |
| 190 | lst = [] |
| 191 | for key in order: |
| 192 | val = gd[key] |
| 193 | if val is None: |
| 194 | break |
| 195 | lst.append(int(val)) |
| 196 | return datetime.datetime(*lst) |
| 197 | |
| 198 | def _dateToString(d): |
| 199 | return '%04d-%02d-%02dT%02d:%02d:%02dZ' % ( |
| 200 | d.year, d.month, d.day, |
| 201 | d.hour, d.minute, d.second |
| 202 | ) |
| 203 | |
Just van Rossum | 26e811a | 2004-11-12 08:02:35 +0000 | [diff] [blame] | 204 | |
Just van Rossum | 2dae764 | 2004-11-12 09:36:12 +0000 | [diff] [blame] | 205 | # Regex to find any control chars, except for \t \n and \r |
| 206 | _controlCharPat = re.compile( |
Just van Rossum | b84330d | 2004-11-12 08:14:49 +0000 | [diff] [blame] | 207 | r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f" |
| 208 | r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]") |
Just van Rossum | 26e811a | 2004-11-12 08:02:35 +0000 | [diff] [blame] | 209 | |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 210 | def _escapeAndEncode(text): |
Just van Rossum | 2dae764 | 2004-11-12 09:36:12 +0000 | [diff] [blame] | 211 | m = _controlCharPat.search(text) |
| 212 | if m is not None: |
| 213 | raise ValueError("strings can't contains control characters; " |
| 214 | "use plistlib.Data instead") |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 215 | text = text.replace("\r\n", "\n") # convert DOS line endings |
| 216 | text = text.replace("\r", "\n") # convert Mac line endings |
| 217 | text = text.replace("&", "&") # escape '&' |
| 218 | text = text.replace("<", "<") # escape '<' |
Just van Rossum | 8b8dece | 2004-10-26 10:11:00 +0000 | [diff] [blame] | 219 | text = text.replace(">", ">") # escape '>' |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 220 | return text.encode("utf-8") # encode as UTF-8 |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 221 | |
| 222 | |
Guido van Rossum | 6dab795 | 2007-08-27 17:25:39 +0000 | [diff] [blame] | 223 | PLISTHEADER = b"""\ |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 224 | <?xml version="1.0" encoding="UTF-8"?> |
| 225 | <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 226 | """ |
| 227 | |
| 228 | class PlistWriter(DumbXMLWriter): |
| 229 | |
Guido van Rossum | 6dab795 | 2007-08-27 17:25:39 +0000 | [diff] [blame] | 230 | def __init__(self, file, indentLevel=0, indent=b"\t", writeHeader=1): |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 231 | if writeHeader: |
| 232 | file.write(PLISTHEADER) |
| 233 | DumbXMLWriter.__init__(self, file, indentLevel, indent) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 234 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 235 | def writeValue(self, value): |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 236 | if isinstance(value, str): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 237 | self.simpleElement("string", value) |
| 238 | elif isinstance(value, bool): |
| 239 | # must switch for bool before int, as bool is a |
| 240 | # subclass of int... |
| 241 | if value: |
| 242 | self.simpleElement("true") |
| 243 | else: |
| 244 | self.simpleElement("false") |
| 245 | elif isinstance(value, int): |
| 246 | self.simpleElement("integer", str(value)) |
| 247 | elif isinstance(value, float): |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 248 | self.simpleElement("real", repr(value)) |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 249 | elif isinstance(value, dict): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 250 | self.writeDict(value) |
| 251 | elif isinstance(value, Data): |
| 252 | self.writeData(value) |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 253 | elif isinstance(value, datetime.datetime): |
| 254 | self.simpleElement("date", _dateToString(value)) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 255 | elif isinstance(value, (tuple, list)): |
| 256 | self.writeArray(value) |
| 257 | else: |
Just van Rossum | 94af32e | 2003-07-01 20:15:38 +0000 | [diff] [blame] | 258 | raise TypeError("unsuported type: %s" % type(value)) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 259 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 260 | def writeData(self, data): |
| 261 | self.beginElement("data") |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 262 | self.indentLevel -= 1 |
| 263 | maxlinelength = 76 - len(self.indent.replace("\t", " " * 8) * |
| 264 | self.indentLevel) |
| 265 | for line in data.asBase64(maxlinelength).split("\n"): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 266 | if line: |
| 267 | self.writeln(line) |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 268 | self.indentLevel += 1 |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 269 | self.endElement("data") |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 270 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 271 | def writeDict(self, d): |
| 272 | self.beginElement("dict") |
Brett Cannon | b38e2bc | 2007-02-21 21:18:18 +0000 | [diff] [blame] | 273 | items = sorted(d.items()) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 274 | for key, value in items: |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 275 | if not isinstance(key, str): |
Just van Rossum | 94af32e | 2003-07-01 20:15:38 +0000 | [diff] [blame] | 276 | raise TypeError("keys must be strings") |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 277 | self.simpleElement("key", key) |
| 278 | self.writeValue(value) |
| 279 | self.endElement("dict") |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 280 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 281 | def writeArray(self, array): |
| 282 | self.beginElement("array") |
| 283 | for value in array: |
| 284 | self.writeValue(value) |
| 285 | self.endElement("array") |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 286 | |
| 287 | |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 288 | class _InternalDict(dict): |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 289 | |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 290 | # This class is needed while Dict is scheduled for deprecation: |
| 291 | # we only need to warn when a *user* instantiates Dict or when |
| 292 | # the "attribute notation for dict keys" is used. |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 293 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 294 | def __getattr__(self, attr): |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 295 | try: |
| 296 | value = self[attr] |
| 297 | except KeyError: |
Collin Winter | e45be28 | 2007-08-23 00:01:55 +0000 | [diff] [blame] | 298 | raise AttributeError(attr) |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 299 | from warnings import warn |
| 300 | warn("Attribute access from plist dicts is deprecated, use d[key] " |
| 301 | "notation instead", PendingDeprecationWarning) |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 302 | return value |
| 303 | |
| 304 | def __setattr__(self, attr, value): |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 305 | from warnings import warn |
| 306 | warn("Attribute access from plist dicts is deprecated, use d[key] " |
| 307 | "notation instead", PendingDeprecationWarning) |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 308 | self[attr] = value |
| 309 | |
| 310 | def __delattr__(self, attr): |
| 311 | try: |
| 312 | del self[attr] |
| 313 | except KeyError: |
Collin Winter | e45be28 | 2007-08-23 00:01:55 +0000 | [diff] [blame] | 314 | raise AttributeError(attr) |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 315 | from warnings import warn |
| 316 | warn("Attribute access from plist dicts is deprecated, use d[key] " |
| 317 | "notation instead", PendingDeprecationWarning) |
| 318 | |
| 319 | class Dict(_InternalDict): |
| 320 | |
| 321 | def __init__(self, **kwargs): |
| 322 | from warnings import warn |
| 323 | warn("The plistlib.Dict class is deprecated, use builtin dict instead", |
| 324 | PendingDeprecationWarning) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 325 | super().__init__(**kwargs) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 326 | |
| 327 | |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 328 | class Plist(_InternalDict): |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 329 | |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 330 | """This class has been deprecated. Use readPlist() and writePlist() |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 331 | functions instead, together with regular dict objects. |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 332 | """ |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 333 | |
Just van Rossum | 86ca902 | 2004-10-25 16:09:10 +0000 | [diff] [blame] | 334 | def __init__(self, **kwargs): |
| 335 | from warnings import warn |
| 336 | warn("The Plist class is deprecated, use the readPlist() and " |
| 337 | "writePlist() functions instead", PendingDeprecationWarning) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 338 | super().__init__(**kwargs) |
Just van Rossum | 86ca902 | 2004-10-25 16:09:10 +0000 | [diff] [blame] | 339 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 340 | def fromFile(cls, pathOrFile): |
Just van Rossum | 86ca902 | 2004-10-25 16:09:10 +0000 | [diff] [blame] | 341 | """Deprecated. Use the readPlist() function instead.""" |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 342 | rootObject = readPlist(pathOrFile) |
| 343 | plist = cls() |
| 344 | plist.update(rootObject) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 345 | return plist |
| 346 | fromFile = classmethod(fromFile) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 347 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 348 | def write(self, pathOrFile): |
Just van Rossum | 86ca902 | 2004-10-25 16:09:10 +0000 | [diff] [blame] | 349 | """Deprecated. Use the writePlist() function instead.""" |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 350 | writePlist(self, pathOrFile) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 351 | |
| 352 | |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 353 | def _encodeBase64(s, maxlinelength=76): |
| 354 | # copied from base64.encodestring(), with added maxlinelength argument |
| 355 | maxbinsize = (maxlinelength//4)*3 |
| 356 | pieces = [] |
| 357 | for i in range(0, len(s), maxbinsize): |
| 358 | chunk = s[i : i + maxbinsize] |
| 359 | pieces.append(binascii.b2a_base64(chunk)) |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 360 | return b''.join(pieces) |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 361 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 362 | class Data: |
| 363 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 364 | """Wrapper for binary data.""" |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 365 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 366 | def __init__(self, data): |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 367 | if not isinstance(data, bytes): |
| 368 | raise TypeError("data must be as bytes") |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 369 | self.data = data |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 370 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 371 | def fromBase64(cls, data): |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 372 | # base64.decodestring just calls binascii.a2b_base64; |
| 373 | # it seems overkill to use both base64 and binascii. |
| 374 | return cls(binascii.a2b_base64(data)) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 375 | fromBase64 = classmethod(fromBase64) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 376 | |
Just van Rossum | 1f74ef0 | 2004-10-26 10:30:55 +0000 | [diff] [blame] | 377 | def asBase64(self, maxlinelength=76): |
| 378 | return _encodeBase64(self.data, maxlinelength) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 379 | |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 380 | def __eq__(self, other): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 381 | if isinstance(other, self.__class__): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 382 | return self.data == other.data |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 383 | elif isinstance(other, str): |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 384 | return self.data == other |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 385 | else: |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 386 | return id(self) == id(other) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 387 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 388 | def __repr__(self): |
| 389 | return "%s(%s)" % (self.__class__.__name__, repr(self.data)) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 390 | |
| 391 | |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 392 | class PlistParser: |
| 393 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 394 | def __init__(self): |
| 395 | self.stack = [] |
| 396 | self.currentKey = None |
| 397 | self.root = None |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 398 | |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 399 | def parse(self, fileobj): |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 400 | from xml.parsers.expat import ParserCreate |
| 401 | parser = ParserCreate() |
| 402 | parser.StartElementHandler = self.handleBeginElement |
| 403 | parser.EndElementHandler = self.handleEndElement |
| 404 | parser.CharacterDataHandler = self.handleData |
Just van Rossum | 95387a1 | 2004-10-25 15:10:42 +0000 | [diff] [blame] | 405 | parser.ParseFile(fileobj) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 406 | return self.root |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 407 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 408 | def handleBeginElement(self, element, attrs): |
| 409 | self.data = [] |
| 410 | handler = getattr(self, "begin_" + element, None) |
| 411 | if handler is not None: |
| 412 | handler(attrs) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 413 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 414 | def handleEndElement(self, element): |
| 415 | handler = getattr(self, "end_" + element, None) |
| 416 | if handler is not None: |
| 417 | handler() |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 418 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 419 | def handleData(self, data): |
| 420 | self.data.append(data) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 421 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 422 | def addObject(self, value): |
| 423 | if self.currentKey is not None: |
| 424 | self.stack[-1][self.currentKey] = value |
| 425 | self.currentKey = None |
| 426 | elif not self.stack: |
| 427 | # this is the root object |
Just van Rossum | 4c3d054 | 2004-10-02 08:40:47 +0000 | [diff] [blame] | 428 | self.root = value |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 429 | else: |
| 430 | self.stack[-1].append(value) |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 431 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 432 | def getData(self): |
Guido van Rossum | cd869d8 | 2007-08-07 14:26:40 +0000 | [diff] [blame] | 433 | data = ''.join(self.data) |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 434 | self.data = [] |
| 435 | return data |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 436 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 437 | # element handlers |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 438 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 439 | def begin_dict(self, attrs): |
Just van Rossum | 368c0b2 | 2004-10-26 07:38:16 +0000 | [diff] [blame] | 440 | d = _InternalDict() |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 441 | self.addObject(d) |
| 442 | self.stack.append(d) |
| 443 | def end_dict(self): |
| 444 | self.stack.pop() |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 445 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 446 | def end_key(self): |
| 447 | self.currentKey = self.getData() |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 448 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 449 | def begin_array(self, attrs): |
| 450 | a = [] |
| 451 | self.addObject(a) |
| 452 | self.stack.append(a) |
| 453 | def end_array(self): |
| 454 | self.stack.pop() |
Just van Rossum | 0ec2744 | 2002-11-19 22:01:02 +0000 | [diff] [blame] | 455 | |
Jack Jansen | 0ae3220 | 2003-04-09 13:25:43 +0000 | [diff] [blame] | 456 | def end_true(self): |
| 457 | self.addObject(True) |
| 458 | def end_false(self): |
| 459 | self.addObject(False) |
| 460 | def end_integer(self): |
| 461 | self.addObject(int(self.getData())) |
| 462 | def end_real(self): |
| 463 | self.addObject(float(self.getData())) |
| 464 | def end_string(self): |
| 465 | self.addObject(self.getData()) |
| 466 | def end_data(self): |
| 467 | self.addObject(Data.fromBase64(self.getData())) |
| 468 | def end_date(self): |
Just van Rossum | 7c94487 | 2004-10-26 07:20:26 +0000 | [diff] [blame] | 469 | self.addObject(_dateFromString(self.getData())) |