无法在Python中使用xattr设置MacOS Finder注释元数据

2024-04-29 04:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

作为大型Python项目的一部分,在finder中查看特定于文件的注释是可取的。因此,我试图在Big Sur上运行Python 3.8.2时,为4500个文件设置finder注释。我使用osxmetadata包实现了这一点,但它需要2-3分钟,这可能是因为调用了AppleScript

Python本身能让finder注释保持不变吗?如果是这样的话,怎么做?或者,如果您必须接触Python以外的领域,是否有比运行Applescript 4500次更有效的方法

使用xattr并不能奏效。下面的代码成功地将扩展属性设置为与Get Info或osxmetadata相同的值。但是字符串/注释不会反映在查找器中

import xattr
import plistlib
from plistlib import FMT_BINARY

file = 'test.json'
bplist = plistlib.dumps('Hello World', fmt=FMT_BINARY)

xattr.setxattr(file, 'com.apple.metadata:kMDItemFinderComment', bplist)

终端中的结果:

% xattr -pl com.apple.metadata:kMDItemFinderComment test.json
0000   62 70 6C 69 73 74 30 30 5B 48 65 6C 6C 6F 20 57    bplist00[Hello W
0010   6F 72 6C 64 08 00 00 00 00 00 00 01 01 00 00 00    orld............
0020   00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00    ................
0030   00 00 00 00 14                                     .....

更多的调查显示目录的.DS_存储文件没有改变。所以,我想我只是改变了“聚光灯评论”,而不是“查找者评论”(?)。我想为我的各种目录编写一个新的.DS_存储文件,但似乎不可能

如果您对Python或混合解决方案有任何想法,我们将不胜感激。谢谢


Tags: 文件testimportcomjsonapplehellofinder
1条回答
网友
1楼 · 发布于 2024-04-29 04:26:36

我做了一些实验,似乎在调用osascript时会有相当大的开销,所以最好避免对4000个文件中的每个文件调用一次

我发现1000个名为f-1f-2等文件在7秒内运行了以下程序:

#!/bin/bash

osascript <<EOF
repeat with i from 1 to 1000
    set fName to "/Users/mark/f-" & i as string
    set fName to (fName as POSIX file)
    tell application "Finder" to set comment of item fName to "Freddy frog"
end repeat
EOF

然而,如果像这样为每个文件创建一个新的osascript,则需要2分钟以上:

# This takes over 2 minutes with 1000 files
for f in f* ; do
filename=$(realpath "$f")
osascript <<EOF
tell application "Finder" to set comment of item POSIX file "$filename" to "Filename=$filename"
EOF
done

如果您的文件名不是按顺序排列的,您可以沿着这些行列出一个列表,或者从应用程序中其他位置创建的文件中读取文件名:

osascript <<EOF
set filelist to {"f-1", "f-2", "f-3"}
repeat with f in filelist
    set fName to "/Users/mark/" & f
    set fName to (fName as POSIX file)
    tell application "Finder" to set comment of item fName to "Freddy frog"
end repeat
EOF
exit

相关问题 更多 >