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

GP8*_*P89 7 python macos finder

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

我找到的最接近解决方案的是这个,但我似乎无法在任何地方找到模块macfile.我只是不够努力吗?

如果不是,有没有不同的方法来实现这一目标?

jte*_*ace 11

你可以使用xattr模块在python中完成这个.

这是一个例子,主要来自这个问题:

from xattr import xattr
from struct import unpack

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[u'com.apple.FinderInfo']
    flags = unpack(32*'B', finder_attrs)
    color = flags[9] >> 1 & 7
except KeyError:
    color = 0

print colornames[color]
Run Code Online (Sandbox Code Playgroud)

由于我用红色标签为此文件着色,因此'red'我会打印出来.您可以使用xattr模块将新标签写回磁盘.


chb*_*own 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')
Run Code Online (Sandbox Code Playgroud)


小智 5

我不知道这个问题是否仍然与任何人相关,但有一个新的软件包“mac-tag”可以解决这个问题。

pip install mac-tag
Run Code Online (Sandbox Code Playgroud)

然后你就有这样的功能:

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
Run Code Online (Sandbox Code Playgroud)

完整文档位于: https: //pypi.org/project/mac-tag/