views:

28

answers:

1

I want to write the python equivalent of mdfind. I want to use the .Spotlight-V100 metadata and I cannot find a description for the metadata db format used, but NSMetadataQuery seems to be what I need. I'd like to do this in python using the built in Obj-C bindings, but have not been able to figure out the correct incantation to get it to work. Not sure if the problem is the asynchronous nature of the call or I'm just wiring things together incorrectly.

A simple example giving the equivalent of of "mdfind " would be fine for a start.

A: 

I got a very simple version working. I don't quite have the predicate correct, as the equivalent mdfind call has additional results. Also, it requires two args, the first is the base pathname to work from with the second being the search term.

Here is the code:

from Cocoa import *

import sys

query = NSMetadataQuery.alloc().init()
query.setPredicate_(NSPredicate.predicateWithFormat_("(kMDItemTextContent = \"" + sys.argv[2] + "\")"))
query.setSearchScopes_(NSArray.arrayWithObject_(sys.argv[1]))
query.startQuery()
NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(5))
query.stopQuery()
print "count: ", len(query.results())
for item in query.results():
    print "item: ", item.valueForAttribute_("kMDItemPath")

The query call is asynchronous, so to be more complete, I should register a callback and have the run loop go continuously. As it is, I do a search for 5 seconds, so if we have a query that would take longer, we will get only partial results.

Tim