I often use Applescript to accomplish basic tasks like opening and closing programs, sometimes going a little more in-depth like running a specific Xcode program's unit tests. I'm learning Python, and I love it. I haven't been able to find much documentation relating AppleScript to Python. My question is: On Mac OS X, can Python be used in place of AppleScript to accomplish the tasks mentioned above? And if so, does anyone know of a good resource to learn more about the topic?
To avoid all the out-dated and so-called "crappy" modules including PyObjC, one can simply debug a script in the Script Editor or Script Debugger (my choice) and then execute it using osascript via Popen. I prefer this so I can ensure the idiosyncrasies of the applications implementation are worked around and Script Debugger has great debugging and browsing tools.
For example:
from subprocess import Popen, PIPE
def get_front_win_id():
"""
Get window id of front Chrome browser window
"""
script = '''
on run {}
set winID to 0
tell application "Google Chrome"
set winID to id of front window
return winID
end tell
end run
'''
args = []
p = Popen(['/usr/bin/osascript', '-'] + args,
stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(script)
winID = stdout.strip()
return int(winID)
Pass args in a list to osascript but they have to be strings so complex data structures can be tedious to marshal and and unmarshal but there is a price for the simplicity. I left off error checking and exception handling/raising for simplicity. TANSTAAFL
Python can't be used to replace the UI & automation duties that AppleScript offers. However since OS X 10.10 (Yosemite) JavaScript can also be used.
See here: https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With