问题
I'm very new to python and applescript. I have a python script which is calling 2 applescripts. I would like to define few global variables in python and pass to applescript 1 , those values will be modified by different functions in applescripts 1, and pass back to python scripts, then pass those values to applescript 2 to use.
I have googled a bit and I tried the following:
in applescript,
on run argv
if (item 1 of argv is start with "x") then
function1(item1 of argv)
else
function2 (item 1 of argv)
function3 (item 2 of argv)
end run
on function1 (var)
set var to (something code to get value from interaction with user)
return var
end function1
in python script import os import sys
os.system ('osascript Setup.scpt')
variable1 = sys.argv[1]
variable2 = sys.argv[2]
in the applescript2, i did similar thing as applescirpt1.
However, this didn't work. I tried to print out all the argv in both scripts, looks like the values are not correctly passed. Can anyone give me more direction on this? Thanks!
回答1:
os.system()
: Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations.
Changes to sys.stdin, sys.stout
are not reflected in the environment of the executed command.
The return value is the exit status, not the osascript output.
Use subprocess.Popen:
import os, sys, commands
from subprocess import Popen, PIPE
var1 = sys.argv[1]
var2 = sys.argv[2]
(var3, tError) = Popen(['osascript', '/Setup.scpt', var1, var2], stdout=PIPE).communicate()
print var1
print var2
print var3
The osascript
command always returns a string
.
if the AppleScript return a list
, the string in python will be separated by a comma and a space.
回答2:
You have to return something from the "on run" handler in applescript otherwise the returned result is only the result of the last line of code. So you'll want to do something like this...
on run argv
set returnList to {}
if (item 1 of argv starts with "x") then
set end of returnList to function1(item1 of argv)
else
set end of returnList to function2(item 1 of argv)
set end of returnList to function3(item 2 of argv)
end if
return returnList
end run
Also your functions will need to look something like this if you want the user to supply something. Note that I'm telling the Finder to show the dialog. That's because you are running this from python and it will error if some application doesn't handle the user interaction.
on function1(var)
tell application "Finder"
activate
set var to text returned of (display dialog "Enter a value" default answer "")
end tell
return var
end function1
来源:https://stackoverflow.com/questions/13502836/pass-and-receive-values-between-python-script-and-applescript