2011-11-30 84 views

回答

11

您可以使用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模塊將新標籤寫回磁盤。

+0

你知道是否可以用這種方式設置顏色?編輯:嗯只是有一個發揮,這不適用於文件夾。可能需要找到其他的東西 – GP89

+0

是的,只需更新顏色位,然後調用''xattrs.set'' – jterrace

+1

@ GP89剛剛測試過,它對我的​​文件夾來說工作正常 – jterrace

4

如果你關注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') 
0

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") 
+0

至少在OSX 10.9.5中,文件似乎不再有「label_index」。我多年來一直使用類似的代碼,但恢復舊項目不再有用,而另一種方法卻行。 – Hraban

相關問題