【问题标题】:How can I parse the contents of text in a variable formatted as a plist using applescript?如何解析使用applescript格式化为plist的变量中的文本内容?
【发布时间】:2018-01-11 11:50:32
【问题描述】:

我想提取 Apple Mac 上已安装应用程序的一些详细信息。我认为在没有任何额外依赖项的情况下在一堆 Mac 上运行它的最便携方式是使用 Applescript。

我可以通过运行得到一个包含 plist 格式的已安装应用程序的变量:

set theAppsList to do shell script "system_profiler SPApplicationsDataType -xml"

但我找不到告诉 Applescript 将此文本解析为 plist 的方法。所有记录在案的 plist 示例都显示了将文件路径传递给 Applescript 的形式:

tell application "System Events" to tell property list file thePropertyListFilePath to ....

但是如何将我从 shell 脚本接收的原始 plist 文本作为 plist 对象处理?是否有一些等效的伪代码:

myPlist = new property list (theAppsList)

这会在内存中创建一个新的 plist 对象吗?

【问题讨论】:

    标签: applescript plist


    【解决方案1】:

    将数据视为 XML 数据,AppleScript 可以将其解析为存储在变量中的文本数据。这是我运行do shell script 行时系统返回的部分文本数据:

        <?xml version=\"1.0\" encoding=\"UTF-8\"?>
        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
        <plist version=\"1.0\">
        <array>
            <dict>
                <key>_SPCommandLineArguments</key>
                        .
                        .
                        .
                <key>_items</key>
                <array> --> ① 
                    <dict> --> ② 
                        <key>_name</key>
                        <string>Little Snitch Software Update</string> --> ③ 
                        .
                        .
                        .
    

    以下 AppleScript 将标记为 ① 和 ② 的 XML 元素隔离开来,并将它们的数据存储为列表,最终可以从中检索每个应用程序的信息(例如,标记为 ③ 的元素表示第一个应用程序的名称):

        tell application "System Events"
            -- Creates a new XML data object and stores it in memory
            if not (exists XML data "AppData") then ¬
                set XMLAppData to make new XML data ¬
                    with properties ¬
                    {name:"AppData", text:theAppsList}
    
            -- array element labelled ① 
            tell XML data "AppData" to ¬
                set AppArray to item 2 of (XML elements of ¬
                    XML element "dict" of XML element "array" of ¬
                    XML element "plist" whose name is "array")
    
            -- dict element labelled ② 
            set AppsDataArray to every XML element in AppArray whose name is "dict"
            -- The number of applications installed
            set n to number of items in AppsDataArray
    
            -- Retrieving ③ from the AppsDataArray list
            -- (the name of the first application)
            get value of XML element "string" of item 1 in AppsDataArray
        end tell
    

    我相信XML data 对象会在大约 5 分钟的空闲时间后从内存中消失。否则,您可以使用delete XML data "AppData"delete every XML data 手动删除它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2021-08-04
      • 2019-11-29
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多