Last Updated on 2022-07-22 by Clay
AppleScript is a native scripting language on Mac OS, and it is useful for calling many functions on Mac OS. For example: customize resize an application window size.
It is very difficult for other languages.
But after I combined AppleScript with the Automator tool on Mac OS to create shortcut key functions, I was surprised that the speed of these shortcut keys was actually very, very slow.
Considering the startup speed, I started to perform some execution methods other than Automator, and accidentally found a way to directly execute AppleScript through script programs such as Bash and Python.
This post record how to execute AppleScript in Python program.
AppleScript in Python
There are two methods for executing:
- Use
os.system()
to execute system commands - Use Python package “applescript“
I prefer the first one, because it is simple and clear. But since this package was discovered, there is no loss in recording it together.
Method 1: Use Python package
First we need to install the package:
pip3 install applescript
After installation, we can write a simple AppleScript script (take Dialog for example):
set Message to "You have a new message!"
display dialog Message
And save it to dialog.applescript.
Then we write the Python code to call this script.
# coding: utf-8
import applescript
def main():
r = applescript.run("dialog.applescript")
r.code
if __name__ == "__main__":
main()
Output:
Method 2: os.system()
# coding: utf-8
import os
def main():
# Command
cmd = """osascript -e '
set Message to "You have a new message!"
display dialog Message
'
"""
# Execute
os.system(cmd)
if __name__ == "__main__":
main()
Output:
References
- https://pypi.org/project/applescript/
- https://stackoverflow.com/questions/2940916/how-do-i-embed-an-applescript-in-a-python-script