Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

python - "Sort by random" in OSX Finder setting kMDItemFinderComment to a random hash for every file in a folder?

Finder allows you to sort files by many different attributes.

In the OSX filesystem, there is an attribute on every file called "comments" (com.apple.metadata:kMDItemFinderComment) which allows you to add any arbitrary string data as metadata for that file.

Finder exposes this "comment" attribute in the GUI and you can "sort" by it. I thought I could abuse this attribute to fill in random data for the each files "comments", and then sort by those random comments.

tldr; I'm trying to create "sort by random" functionality (in Finder) with the help of a BASH script and some python.

this does work to achieve that (sort of):

find $1 -type f -print0 | while IFS= read -r -d $'' file; #get a list of files in the dir
  do
  if [[ $file == *.wav ]]
    then
        hash=$(openssl rand -hex 12); #generate a random hash
        osxmetadata --set findercomment "$hash" $file; #set the comment
    fi
done

here i'm using the osxmetadata python utility to do the heavy lifting.

and while it works as intended, but it's really slow:

https://i.stack.imgur.com/d7exk.gif

i'm trying to do this operation on folders with many items, and would frequently be "re-seeding" the files with random comments.

can anyone suggest an optimization i can try to make this faster? i tried using xattrs but that doesn't seem reindex the comments in finder when they update.

question from:https://stackoverflow.com/questions/65909179/sort-by-random-in-osx-finder-setting-kmditemfindercomment-to-a-random-hash-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd wrap the then-clause in a (...)& and add a wait after the loop. Then it will do every file in parallel.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...