Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an AppleScript from within a Python script?

How to run an AppleScript from within a Python script?

The questions says it all.. (On a Mac obviously)

like image 645
GJ. Avatar asked Aug 15 '10 21:08

GJ.


2 Answers

this nice article suggests the simple solution

cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
    os.system(cmd)

though today you'd use the subprocess module instead of os.system, of course.

Be sure to also check page 2 of the article for many more info and options, including appscript.

like image 175
Alex Martelli Avatar answered Sep 28 '22 07:09

Alex Martelli


A subprocess version which allows running an original apple script as-is, without having to escape quotes and other characters which can be tricky. It is a simplified version of the script found here which also does parametrization and proper escaping (Python 2.x).

import subprocess

script = '''tell application "System Events"
    activate
    display dialog "Hello Cocoa!" with title "Sample Cocoa Dialog" default button 2
end tell
'''

proc = subprocess.Popen(['osascript', '-'],
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE)
stdout_output = proc.communicate(script)[0]
print stdout_output

NOTE: If you need to execute more than one script with the same Popen instance then you'll need to write explicitly with proc.stdin.write(script) and read with proc.stdout.read() because communicate() will close the input and output streams.

like image 44
ccpizza Avatar answered Sep 28 '22 07:09

ccpizza