Serializing a Python Object for XML (Apple.plist)

I need to read and serialize objects from and to XML format, in Apple.plist format. What is the most sensible way to do this in Python? Are there any ready-made solutions?

+3
source share
2 answers

Note plistlib .

+7
source

Assuming you are on a Mac, you can use PyObjC.

Here is an example reading from plist, from Using Python for System Administration , slide 27.

from Cocoa import NSDictionary

myfile = "/Library/Preferences/com.apple.SoftwareUpdate.plist"
mydict = NSDictionary.dictionaryWithContentsOfFile_(myfile)

print mydict["LastSuccessfulDate"]

# returns: 2009-08-11 08:38:01 -0600

And an example of writing to plist (which I wrote):

#!/usr/bin/env python

from Cocoa import NSDictionary, NSString

myfile = "~/test.plist"
myfile = NSString.stringByExpandingTildeInPath(myfile)

mydict = {"Nice Number" : 47, "Universal Sum" : 42}
mydict["Vector"] = (10, 20, 30)
mydict["Complex"] = [47, "i^2"]
mydict["Truth"] = True

NSDictionary.dictionaryWithDictionary_(mydict).writeToFile_atomically_(myfile, True)

When I run defaults read ~/testin bash, I get:

{
    Complex =     (
        47,
        "i^2"
    );
    "Nice Number" = 47;
    Truth = 1;
    "Universal Sum" = 42;
    Vector =     (
        10,
        20,
        30
    );
}

And the file looks very good when opened in the Property List Editor.app.

+2

Source: https://habr.com/ru/post/1708593/


All Articles