Get list of printers?

Piyomaru, in another thread, mentioned that there is no command to get the printer list. Many years ago, with the help of many people who know what they are doing (I rarely know what I’m doing), I was able to put together this code to get a list of printers that I could use for printing a file with the lpr command. It isn’t really competent, and if anyone knows a better method, I would be very glad to hear about it:


on run
	selectPrinter()
end run

on selectPrinter()
	set thePrinter to ""
	set theQueue to ""
	set printerNames to (do shell script "lpstat  -l -p | grep -i Description: |awk -F'Description: ' '{print $2}' ")
	set queueNames to (do shell script "lpstat -a | awk -F' accepting' '{print $1}'")
	
	set printerList to (every paragraph of printerNames) as list
	set queueList to (every paragraph of queueNames) as list
	
	if printerList is {} then
		tell application "System Events"
			activate
			display dialog "No printer is available." buttons {"OK"} default button 1 giving up after 3
		end tell
		return
	end if
	
	if the (count of printerList) is 1 then
		set thePrinter to {item 1 of printerList} as string
		set theQueue to {item 1 of queueList} as string
	else
		tell application "SystemUIServer"
			activate
			try
				set thePrinter to (choose from list printerList with title "Printers" with prompt "Select a printer:")
			end try
		end tell
		
		if thePrinter is false then
			tell application "System Events"
				activate
				display dialog "Printing cancelled." buttons {"OK"} default button 1 giving up after 3
			end tell
			return
		else
			set thePrinter to item 1 of thePrinter
			set itemNum to my listPosition(thePrinter, printerList)
			set theQueue to item itemNum in queueList
		end if
		
		if theQueue ends with " not" then
			tell application "System Events"
				activate
				display dialog thePrinter & space & "is not available." buttons {"OK"} default button 1 giving up after 3
			end tell
			return
		end if
		
	end if
	tell application "System Events"
		activate
		display dialog "Selected printer:" & space & thePrinter & "." & return & return & "Its queue is named:" & space & theQueue & "." buttons ("OK") default button 1 giving up after 5
	end tell
	return theQueue
end selectPrinter

on listPosition(thisItem, thisList)
	repeat with i from 1 to the count of thisList
		if item i of thisList is thisItem then return i
	end repeat
	return 0
end listPosition

I wrote this code in 2014.

use AppleScript version “2.4”
use scripting additions
use framework “Foundation”
use framework “AppKit”

set pArray to current application’s NSPrinter’s printerNames
set pList to pArray as list

Scripts to get system information are here.

1 Like