将Python对象序列化为XML(Apple .plist)

时间:2009-05-18 18:51:33

标签: python xml plist

我需要从XML读取和序列化对象,特别是Apple的.plist格式。在Python中最聪明的方法是什么?有没有现成的解决方案?

2 个答案:

答案 0 :(得分:7)

查看plistlib

答案 1 :(得分:2)

假设您使用的是Mac,则可以使用PyObjC。

以下是从Using Python For System Administration,幻灯片27中读取plist的示例。

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

写一个plist的例子(我写的):

#!/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)

当我在bash中运行defaults read ~/test时,我得到:

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

在Property List Editor.app。

中打开文件时看起来非常好