Yierith
Yierith

Reputation: 141

Getting Variable from Applescript and using in Python

Is there any easy way to use an applescript like:

set theText to text returned of (display dialog "Please insert Text here:" default answer "" with title "exchange to python" with icon 1)

And use the "theText" variable in python?

Upvotes: 0

Views: 1502

Answers (2)

Gabriel Ratener
Gabriel Ratener

Reputation: 605

You can also run a python script with command line input from AppleScript:

--make sure to escape properly if needed
set pythonvar to "whatever"
set outputvar to (do shell script "python '/path/to/script' '" & pythonvar & "'")

Ned's example has python calling AppleScript, then returning control to python, this is the other way around. Then in Python access list of parameters:

import sys
var_from_as = sys.argv[1] # for 1rst parameter cause argv[0] is file name
print 'this gets returned to AppleScript' # this gets set to outputvar

Upvotes: 1

Ned Deily
Ned Deily

Reputation: 85105

There are a number of ways to do it. Probably the simplest way, since it does not rely on any third-party Python modules, is to run the script in a child process using the OS X osascript command line utility. By default, osascript returns any output from the AppleScript execution to stdout which can be then be read in Python. You can try it out in the Python interactive interpreter.

With Python 3.4.1:

>>> import subprocess
>>> theText = subprocess.check_output(['osascript', '-e', \
       r'''set theText to text returned of (display dialog "Please insert Text here:" default answer "" with title "exchange to python" with icon 1)'''])
>>> theText
b'Hell\xc3\xb6 W\xc3\xb2rld!\n'
>>> print(theText.decode('UTF-8'))
Hellö Wòrld!

With Python 2.7.7:

>>> theText
'Hell\xc3\xb6 W\xc3\xb2rld!\n'
>>> print(theText.decode('UTF-8'))
Hellö Wòrld!

For a real world application, you'll probably want to do some error checking and/or exception catching.

Upvotes: 0

Related Questions