8

How to run an AppleScript from within a Python script?

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

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

8 Comments

If you going to do any kind of non-trivial Apple Event scripting from Python, you should be using appscript. It's well-designed, mature, and well-supported.
@Ned, sure, but for such a simple, specific purpose as calling a simple bit of applescript, the "stupid trick" of osascript -e and subprocess.call, as suggested in the article's page 1 (well the article as I mentions uses the old os.system, but that's a detail;-) might suffice.
Oh, Alex, I certainly wasn't disagreeing with you!
appscript isn't supported anymore unfortunately
What do you mean "it's not supported anymore"?
|
6

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.

1 Comment

In python 3 this would not work, an additional parameter universal_newlines=True on the popen is needed. See stackoverflow.com/a/45133926/1534775
0

I got the Output folks... Here it's following:

import subprocess
import sys

for i in range(int(sys.argv[1])):
    ip = str(sys.argv[2])
    username = str(sys.argv[3])
    pwd = str(sys.argv[4])

    script = '''tell application "Terminal"
        activate
        do script with command "cd Desktop && python test_switch.py {ip} {username} {pwd}"
        delay 15
    end tell
    '''

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

Comments

0

I was pretty frustrated at the lack of detail in Apple's own documentation regarding how to do this AND to also pass in arguments. I had to send the desired arg (in this case a zoom id) as a string otherwise the argument didn't come through to the applescript app

Here's my code running from python:

f = script if os.path.exists(script) else _tempfile()

if not os.path.exists(script):
            open(f,'w').write(script)
args = ["osascript", f, str(zoom_id)]

kwargs = {'stdout':open(os.devnull, 'wb'),'stderr':open(os.devnull, 'wb')}
        #kwargs.update(params)
proc = subprocess.Popen(args,**kwargs)

and here is my applescript:

on run argv
    set zoom_id to 0
    zoom_id = item 1 in argv
    tell application "zoom.us"
       --do stuff
    end tell
end run

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.