【发布时间】:2011-11-30 15:33:54
【问题描述】:
我一直在尝试找出如何从 python 获取和设置文件标签的颜色。
我找到的最接近解决方案的是this,但我似乎无法在任何地方找到模块 macfile。是我不够努力吗?
如果没有,有其他方法可以实现吗?
【问题讨论】:
我一直在尝试找出如何从 python 获取和设置文件标签的颜色。
我找到的最接近解决方案的是this,但我似乎无法在任何地方找到模块 macfile。是我不够努力吗?
如果没有,有其他方法可以实现吗?
【问题讨论】:
您可以在 python 中使用xattr 模块来执行此操作。
这是一个例子,主要取自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 模块将新标签写回磁盘。
【讨论】:
如果您点击 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')
【讨论】:
我不知道这个问题是否仍然与任何人相关,但有一个新的包“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
【讨论】:
macfile 模块是appscript 模块的一部分,并在"2006-11-20 -- 0.2.0" 中重命名为mactypes
使用这个模块,这里有两个函数来获取和设置 appscript 版本 1.0 的查找器标签:
from appscript import app
from mactypes import File as MacFile
# Note these label names could be changed in the Finder preferences,
# but the colours are fixed
FINDER_LABEL_NAMES = {
0: 'none',
1: 'orange',
2: 'red',
3: 'yellow',
4: 'blue',
5: 'purple',
6: 'green',
7: 'gray',
}
def finder_label(path):
"""Get the Finder label colour for the given path
>>> finder_label("/tmp/example.txt")
'green'
"""
idx = app('Finder').items[MacFile(path)].label_index.get()
return FINDER_LABEL_NAMES[idx]
def set_finder_label(path, label):
"""Set the Finder label by colour
>>> set_finder_label("/tmp/example.txt", "blue")
"""
label_rev = {v:k for k, v in FINDER_LABEL_NAMES.items()}
available = label_rev.keys()
if label not in available:
raise ValueError(
"%r not in available labels of %s" % (
label,
", ".join(available)))
app('Finder').items[MacFile(path)].label_index.set(label_rev[label])
if __name__ == "__main__":
# Touch file
path = "blah"
open(path, "w").close()
# Toggle label colour
if finder_label(path) == "green":
set_finder_label(path, "red")
else:
set_finder_label(path, "green")
【讨论】: