Search code examples
pythoncommentsapplescriptspotlight

Get spotlight comments from file using python


I'm trying to get spotlight comments with python. All I need now is the ability for popen to return whatever the shell would normally output if running the same thing. once i have a string in python then I can filter it properly.

import sys, os, glob

paths = glob.glob("*.wav")
print paths

for soundFile in paths:
    #soundFile = os.path.abspath(soundFile)
    result = os.popen("xattr -p com.apple.metadata:kMDItemFinderComment "+soundFile+" | xxd -r -p |plutil -convert xml1 -o - -")
    print result

Solution

  • I don't know what the equivalent of this would be in Python, but you can use xattr to print the extended attribute as an XML property list.

    #!/usr/bin/env ruby -KU
    
    require 'cgi'
    
    plist = `xattr -p com.apple.metadata:kMDItemFinderComment test.txt |
    xxd -r -p | plutil -convert xml1 -o - -`
    puts CGI.unescapeHTML(plist.scan(/<string>(.*?)<\/string>/m)[0][0])
    

    I forgot about mdls -n kMDItemFinderComment. Finder doesn't always store the comments in extended attributes anyway.