Using appscript together with an AppleScript droplet

It seems that a lot of people are looking for sample code that shows how to use appscript together with an AppleScript droplet, which acts on Finder items dropped onto its icon.

The easiest way to do this is to write a generic AppleScript droplet that creates a large string containing the quoted Posix paths of all dropped items and then executes a Python/Ruby script located in the application bundle with the generated item paths passed as arguments.

That might sound complicated, and so I have created a small sample script which you can download and then test and inspect on your Mac. Please note, that you need to have py-appscript installed to successfully test it:

dropycol ¢ set color label of dropped Finder items using appscript (ca. 33.5 KB)

The sample script does nothing special, it just sets the color label of dropped Finder items to a random color using the py-appscript module. If an item already has a color label, the label is reset to colorless, so that you can easily clean up the mess afterwards.

Of course, the principal is the same for Ruby scripts using the rb-appscript module.

Important: Opening and saving the below script code in Script Editor won’t result in a usable AppleScript! That is because the presented AppleScript internally relies on a Python script, which is located inside its Application bundle. Therefor please download the complete script here.

This is the AppleScript droplet code that iterates over the dropped Finder items:

property mytitle : "dropycol"

on open dropitems
		-- creating a large string containing all the 
		-- quoted Posix paths of the dropped items
		set strfilepaths to ""
		set countdropitems to length of dropitems
		repeat with i from 1 to countdropitems
			set dropitempath to (item i of dropitems) as Unicode text
			if i is equal to dropitems then
				set strfilepaths to strfilepaths & quoted form of (POSIX path of dropitempath)
				set strfilepaths to strfilepaths & quoted form of (POSIX path of dropitempath) & space
			end if
		end repeat
		-- getting the path to the Python script inside the AppleScript bundle
		set mypath to ((path to me) as Unicode text)
		set pyscriptpath to quoted form of (POSIX path of (mypath & ""))
		-- executing the Python script with the item paths passed as arguments
		set cmd to "python" & space & pyscriptpath & space & strfilepaths
		set cmd to cmd as «class utf8»
		set shellresult to do shell script cmd
		-- catching unexpected errors
	on error errmsg number errnum
		tell me
			display dialog "Sorry, an error occured:" & return & return & errmsg & " (" & errnum & ")" buttons {"OK"} default button 1 with icon stop with title mytitle
		end tell
	end try
end open

This is the code of the Python script using appscript to set/reset the color label of Finder items.