从Python获取和设置mac文件和文件夹查找器标签

问题描述 投票:8回答:4

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

我找到的最接近解决方案的是this,但是我似乎在任何地方都找不到模块macfile。我只是看起来不够努力吗?

是否有其他方法可以实现这一目标?

python macos finder
4个回答
12
投票

您可以使用xattr模块在python中执行此操作。

这里是一个例子,主要来自this question

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模块将新标签写回磁盘。


4
投票

[如果您按照favouretti的链接然后向下滚动一点,则有一个链接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')

1
投票

我不知道这个问题是否仍然与任何人相关,但是有一个新的软件包“ 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/


0
投票

macfile模块是appscript模块的一部分,并在appscript中重命名为mactypes

使用此模块,这是两个用于使用appscript版本1.0获取和设置finder标签的功能:

"2006-11-20 -- 0.2.0"
© www.soinside.com 2019 - 2024. All rights reserved.