Noupin
Noupin

Reputation: 15

AppleScript Variables in Python

Why does this not work? I am trying to set a python variable equal to applescript code.

from os import system
cmd = """osascript<<END
    tell application "SpeechRecognitionServer"
    set theResponse to listen for {"good", "bad", "weather"}
    end tell
    END"""
response = str(system(cmd))
print response
if response == "good":
    print "Ok"

Upvotes: 0

Views: 494

Answers (3)

Carlos Fragoso
Carlos Fragoso

Reputation: 23

This worked for me, after turning on dictation on system preferences and selecting enhanced dictation

from os import system
cmd = """osascript<<END
tell application "SpeechRecognitionServer"
set theResponse to listen for {"good", "bad", "weather"}
end tell
"""
response = str(system(cmd))
   print(response)
if response == "good":
  print("Ok")

Upvotes: 0

benwiggy
benwiggy

Reputation: 2739

This is the easiest way to get results from an AppleScript in python:

from Foundation import NSAppleScript

textOfMyScript = """
tell application "SpeechRecognitionServer"
    set theResponse to listen for {"good", "bad", "weather"}
end tell
"""
myScript = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript)
results, err = myScript.executeAndReturnError_(None)

myWord = results.stringValue()
if myWord == "good":
    print ("OK")

If the Apple Event returns more than one thing, then you need to use:

myData = results.descriptorAtIndex_(2).stringValue()

where 2 is the index (starting at 1). You'll probably want some error handling.

Upvotes: 0

foo
foo

Reputation: 3259

According to Python documentation, os.system() only returns an exit code; any output goes to stdout. Use subprocess instead. There's an example here.

If you need to pass more complex arguments or call specific handlers, another option is to use NSAppleScript via PyObjC; there's a convenience wrapper here.

Upvotes: 1

Related Questions