How to set the icon for a folder or file with a little bit of PyObjC

There may be situations in which you need to set an icon for a folder or file. If you start searching online, you might run into a bunch of recommendations that rely on Xcode command line tools or methods that simply no longer work.

The following method is quite simple because it only relies on the Python Objective-C bridge which has been bundled with macOS for many years now. The relevant API is in the NSWorkspace.

For just the PyObjC code, here it is taken from a StackOverFlow answer:

#!/usr/bin/python
# https://developer.apple.com/documentation/appkit/nsworkspace/1529882-seticon?language=objc
# Argument 1: Path to icon
# Argument 2: Path to folder/file to set icon for

import Cocoa
import sys

Cocoa.NSWorkspace.sharedWorkspace().setIcon_forFile_options_(Cocoa.NSImage.alloc().initWithContentsOfFile_(sys.argv[1].decode('utf-8')), sys.argv[2].decode('utf-8'), 0) or sys.exit("Unable to set file icon")

 
And if you want to make use of that code in a Bash script, it’s not too hard:

#!/bin/bash
# This is PyObjC code that can be used in a bash script
# https://developer.apple.com/documentation/appkit/nsworkspace/1529882-seticon?language=objc

FolderIcon="/path/to/icon.icns"
PathToSetIconFor="/path/to/folder"

setFolderIcon (){
/usr/bin/python - "$1" "$2" << EOF
import Cocoa
import sys
Cocoa.NSWorkspace.sharedWorkspace().setIcon_forFile_options_(Cocoa.NSImage.alloc().initWithContentsOfFile_(sys.argv[1].decode('utf-8')), sys.argv[2].decode('utf-8'), 0)
EOF
}
setFolderIcon "$FolderIcon" "$PathToSetIconFor"

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s