Skip to content

Instantly share code, notes, and snippets.

@waylan
Created December 2, 2018 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save waylan/73b749ce50c2c3df586e910b460217b2 to your computer and use it in GitHub Desktop.
Save waylan/73b749ce50c2c3df586e910b460217b2 to your computer and use it in GitHub Desktop.
Call Applescripts from Python
#!/usr/bin/python
# From http://www.leancrew.com/all-this/2013/03/combining-python-and-applescript/
# Updated for Python 3
import subprocess
def asrun(ascript):
"Run the given AppleScript and return the standard output and error."
result = subprocess.run(
['osascript', '-'],
input=ascript,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
check=True
)
return result.stdout
def asquote(astr):
"Return the AppleScript equivalent of the given string."
astr = astr.replace('"', '" & quote & "')
return '"{}"'.format(astr)
if __name__ == '__main__':
# Exmaple usage
subject = 'A new email'
body = '''This is the body of my "email."
I hope it comes out right.
Regards,
Dr. Drang
'''
ascript = '''
tell application "Mail"
activate
make new outgoing message with properties {{visible:true, subject:{0}, content:{1}}}
end tell
'''.format(asquote(subject), asquote(body))
print(ascript)
asrun(ascript)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment