-
-
Save dublado/b92f4a76e557287022481f3ce43de50f to your computer and use it in GitHub Desktop.
Call Applescripts from Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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