【问题标题】:Serializing a Python Object to XML (Apple .plist)将 Python 对象序列化为 XML (Apple .plist)
【发布时间】:2009-05-18 18:51:32
【问题描述】:

我需要从 XML 读取和序列化对象,尤其是 Apple 的 .plist 格式。在 Python 中最智能的方法是什么?有现成的解决方案吗?

【问题讨论】:

    标签: python xml plist


    【解决方案1】:

    查看plistlib

    【讨论】:

      【解决方案2】:

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

      这是一个从 plist 读取的示例,来自 Using Python For System Administration,幻灯片 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
      

      还有一个写入 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 中打开该文件时看起来非常漂亮。

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 2011-01-07
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 2020-05-10
        相关资源
        最近更新 更多