微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

作为更大的 Python 项目的一部分,在查找器中可以看到特定于文件的注释是可取的。因此,我正在尝试使用在 Big Sur 上运行的 Python 3.8.2 为 4500 个文件设置查找程序注释。我已经使用 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_Store 文件没有改变。所以,我想我只是改变了“聚光灯评论”而不是“发现者评论”(?)。我想过为我的各种目录编写一个新的 .DS_Store 文件,但似乎不可能。

对问题的任何有关 Python 或混合解决方案的想法将不胜感激。谢谢!

解决方法

我做了一些实验,似乎调用 osascript 的开销相当大,因此最好避免为 4,000 个文件中的每个文件调用一次。

我发现 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。