Skip to content

Instantly share code, notes, and snippets.

@tofias tofias/
Last active Oct 12, 2018

What would you like to do?
# v. 2014-09-18
# based on by Dr. Drang
import subprocess
def asrun(ascript):
"Run the given AppleScript and return the standard output and error."
osa = subprocess.Popen(['osascript', '-'],
return osa.communicate(ascript)[0]
def asquote(astr):
"Return the AppleScript equivalent of the given string."
astr = astr.replace('"', '" & quote & "')
return '"{}"'.format(astr)
def asdialog(msg='', btns='OK', input=None, title=''):
"Generate a dialog box with optional input text, returns a response dictionary."
# User might have entered btns as a string, or more than 3, so help them out
# n.b. need to build the button commponent before the main AppleScript build
lenbtns = len(btns)
if isinstance(btns, basestring):
lenbtns = 1
if lenbtns < 3:
btnno = lenbtns
if lenbtns == 1:
_btns = asquote(str(btns))
elif lenbtns == 2:
_btns = asquote(btns[0]) + ',' + asquote(btns[1])
btnno = 3
_btns = asquote(btns[0]) + ',' + asquote(btns[1]) + ',' + asquote(btns[2])
# Don't ask, don't tell (for returned text if user didn't ask for returned text)
if input:
_input = '''default answer {0}'''.format(asquote(input))
_textret = '''"\": \"" & quoted form of the text returned of theReturn &'''
_input = ''
_textret = ''
# This is where the magic happens
asd = '''
set theReturn to (display dialog {0} {1} with title {2} buttons {{ {3} }} default button {4})
'''.format(asquote(msg), _input, asquote(title), _btns, btnno, _textret)
# Massage the output into a dict
asran = asrun(asd).split(', text returned:')
_btn = asran[0].replace(' returned','').replace('button:','')
# I will admit this is a kludgie way of dealing with a user cancel
if _btn == '':
_btn = 'Cancel '
# Need to trim off trailing newline character because AppleScript
if len(asran) == 2:
return {'button': _btn, 'text': str(asran[1])[:-1]}
return {'button': _btn[:-1], 'text': None}
# Just some quick little tests for
from applescript import asdialog
def prt(this_run):
print '\r\rThis run has... ' + this_run
print "output['button'] = " + str(output['button'])
if output.has_key('text'):
print "output['text'] = " + str(output['text'])
print "There is no text to print"
msg = 'This is a bespoke dialog message.'
title = 'Take this artisanal action?'
btns = 'Cancel', 'Publish', 'Save Draft', 'Greedy'
input = 'Here is some lovely sample input text.'
output = asdialog(msg)
output = asdialog(msg, btns=btns)
prt('msg, btns')
output = asdialog(msg, btns=btns, title=title)
prt('msg, btns, title')
output = asdialog(msg, btns=btns, title=title, input=input)
prt('msg, btns, title, input')
output = asdialog()
prt('no parameters given')

This comment has been minimized.

Copy link
Owner Author

tofias commented Sep 18, 2014

Okay, the first version drooled, this one rules.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.