从Python获取和设置Mac文件夹Finder标签

12 投票
5 回答
5804 浏览
提问于 2025-04-17 07:24

我一直在尝试找出如何通过Python获取和设置文件标签的颜色。

我找到的最接近解决方案的东西是这个链接,但我似乎找不到macfile这个模块。我是不是没有好好找呢?

如果没有这个模块,还有其他方法可以实现吗?

5 个回答

5

我不知道这个问题现在还有没有人关心,但有一个新的工具包叫“mac-tag”,可以解决这个问题。

pip install mac-tag

然后你可以使用一些这样的功能:

function    __doc__
mac_tag.add(tags, path) # add tags to path(s)
mac_tag.find(tags, path=None)   # return a list of all paths with tags, limited to path(s) if present
mac_tag.get(path)   # return dict where keys are paths, values are lists of tags. equivalent of tag -l
mac_tag.match(tags, path)   # return a list of paths with with matching tags
mac_tag.parse_list_output(out)  # parse tag -l output and return dict
mac_tag.remove(tags, path)  # remove tags from path(s)
mac_tag.update(tags, path)  # set path(s) tags. equivalent of `tag -s

完整的文档可以在这里找到: https://pypi.org/project/mac-tag/

5

如果你点击favoretti的链接,然后往下滚动一点,你会看到一个链接,指向https://github.com/danthedeckie/display_colors。这个链接通过xattr来实现这个功能,但没有进行二进制操作。我稍微修改了一下他的代码:

from xattr import xattr

def set_label(filename, color_name):
    colors = ['none', 'gray', 'green', 'purple', 'blue', 'yellow', 'red', 'orange']
    key = u'com.apple.FinderInfo'
    attrs = xattr(filename)
    current = attrs.copy().get(key, chr(0)*32)
    changed = current[:9] + chr(colors.index(color_name)*2) + current[10:]
    attrs.set(key, changed)

set_label('/Users/chbrown/Desktop', 'green')
14

你可以在Python中使用xattr这个模块来实现这个功能。

下面是一个例子,主要来自于这个问题

from xattr import xattr

colornames = {
    0: 'none',
    1: 'gray',
    2: 'green',
    3: 'purple',
    4: 'blue',
    5: 'yellow',
    6: 'red',
    7: 'orange',
}

attrs = xattr('./test.cpp')

try:
    finder_attrs = attrs['com.apple.FinderInfo']
    color = finder_attrs[9] >> 1 & 7
except KeyError:
    color = 0

print colornames[color]

因为我给这个文件加了红色标签,所以它会打印出'red'。你也可以使用xattr模块把新的标签写回到磁盘上。

撰写回答