开发者

How can I write a python script equivalent of mdfind using PyObjC bindings and NSMetadataQuery?

开发者 https://www.devze.com 2023-01-21 15:05 出处:网络
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 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消