1

我对python和applescript很陌生。我有一个调用 2 个 applescripts 的 python 脚本。我想在 python 中定义几个全局变量并传递给 applescript 1 ,这些值将由 applescripts 1 中的不同函数修改,然后传回 python 脚本,然后将这些值传递给 applescript 2 使用。

我用谷歌搜索了一下,我尝试了以下方法:

在苹果脚本中,

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

在 python 脚本中导入 os 导入 sys

os.system ('osascript Setup.scpt')
variable1 = sys.argv[1]
variable2 = sys.argv[2]

在applescript2中,我做了与applescirpt1类似的事情。

然而,这并没有奏效。我试图打印出两个脚本中的所有 argv,看起来值没有正确传递。谁能给我更多的指导?谢谢!

4

2 回答 2

0

您必须从 applescript 中的“on run”处理程序返回一些东西,否则返回的结果只是最后一行代码的结果。所以你会想做这样的事情......

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

如果您希望用户提供一些东西,您的功能也需要看起来像这样。请注意,我告诉 Finder 显示对话框。那是因为您是从 python 运行它,如果某些应用程序不处理用户交互,它将出错。

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
于 2012-11-22T02:04:41.323 回答
0

os.system():在子shell中执行命令(字符串)。这是通过调用标准 C 函数 system() 来实现的,并且具有相同的限制。

更改sys.stdin, sys.stout不会反映在执行命令的环境中。返回值是退出状态,而不是 osascript 输出。

使用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

osascript命令总是返回一个string. 如果 AppleScript 返回 a list,则 python 中的字符串将用逗号和空格分隔。

于 2012-11-23T08:39:57.537 回答