2

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.

4

1 回答 1

1

我得到了一个非常简单的版本。我的谓词不太正确,因为等效的mdfind调用有额外的结果。此外,它需要两个参数,第一个是基本路径名,第二个是搜索词。

这是代码:

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")

查询调用是异步的,所以为了更完整,我应该注册一个回调并让运行循环连续运行。事实上,我搜索了 5 秒,所以如果我们有一个需要更长时间的查询,我们只会得到部分结果。

于 2010-10-22T18:24:41.470 回答