One of the things I've done for the upcoming version of Houdini for OS X is to fancy up some of the icons a bit. Our build system is still based on Makefiles. That means I've got to have some way to set a file's icon from the shell.

There are a number of solutions out there using AppleScript. However, Leopard's now standard inclusion of PyObjC makes things even more simple. Here's the Python code you need to set a files icon, given any image.

from AppKit import *

def set_icon(icon_path, file_path):
    image = NSImage.alloc().initWithContentsOfFile_(icon_path)

    workspace = NSWorkspace.sharedWorkspace()
    workspace.setIcon_forFile_options_(image, file_path, 
        NSExcludeQuickDrawElementsIconCreationOption)

Pretty simple. There is one thing to watch out for though. Since this is a Cocoa routine, it needs to access the window server. And therefore will not work unless the user running the script is logged into the console. That's a bit of a pain for automated builds, but not a big deal for most people.

Here's a more complete program. This implements a shell program for setting icons.

#!/usr/bin/python

from AppKit import *
import sys

def main():
    if len(sys.argv) != 3:
        sys.stderr.write('Usage: set_icon.py <icon path> <file path>\n')
        sys.exit(-1)

    icon = sys.argv[1]
    file = sys.argv[2]

    set_icon(icon, file)

def set_icon(icon_path, file_path):
    image = NSImage.alloc().initWithContentsOfFile_(icon_path)

    workspace = NSWorkspace.sharedWorkspace()
    workspace.setIcon_forFile_options_(image, file_path, 
        NSExcludeQuickDrawElementsIconCreationOption)

if __name__ == '__main__':
    main()
blog comments powered by Disqus
Disclaimer: The above statements and opinions are my own and do not represent those of my employer.