How do I embed an AppleScript in a Python script?
Use subprocess:
from subprocess import Popen, PIPE
scpt = '''
on run {x, y}
return x + y
end run'''
args = ['2', '2']
p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)
Example 3 in this article suggests:
#!/usr/bin/env python
#sleepy-mac.py
#makes my mac very sleepy
import os
cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
os.system(cmd)
stupidtrick()
These days, however, subsystem.Popen
is usually preferred over os.system
(the article is from three years ago, when nobody screamed on seeing an os.system
call;-).