我一直在試圖找出如何獲取和設置python文件標籤的顏色。從Python獲取和設置mac文件和文件夾查找程序標籤
我發現一個解決方案最接近的東西是this,但我似乎無法在任何地方找到模塊macfile。我只是不夠努力?
有沒有不同的方式來實現這一點,如果不是?
我一直在試圖找出如何獲取和設置python文件標籤的顏色。從Python獲取和設置mac文件和文件夾查找程序標籤
我發現一個解決方案最接近的東西是this,但我似乎無法在任何地方找到模塊macfile。我只是不夠努力?
有沒有不同的方式來實現這一點,如果不是?
您可以使用xattr模塊在Python中執行此操作。
下面是一個例子,從this question大多采取:
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]
因爲我有彩色文件與紅色標籤,這種打印'red'
我。您可以使用xattr模塊將新標籤寫回磁盤。
如果你關注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')
的macfile
模塊是appscript
模塊的一部分,並更名爲mactypes
在"2006-11-20 -- 0.2.0"
使用此模塊,這裏有兩個函數來獲取和設置取景器標籤與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")
至少在OSX 10.9.5中,文件似乎不再有「label_index」。我多年來一直使用類似的代碼,但恢復舊項目不再有用,而另一種方法卻行。 – Hraban
你知道是否可以用這種方式設置顏色?編輯:嗯只是有一個發揮,這不適用於文件夾。可能需要找到其他的東西 – GP89
是的,只需更新顏色位,然後調用''xattrs.set'' – jterrace
@ GP89剛剛測試過,它對我的文件夾來說工作正常 – jterrace