这有效(打印,例如“ 3个参数”):

to run argv
    do shell script "echo " & (count argv) & " arguments"
end run

这不是(仅打印“参数3:三”,而不是前两个参数):

to run argv
    do shell script "echo " & (count argv) & " arguments"

    repeat with i from 1 to (count argv)
        do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'"
    end repeat
end run

在这两种情况下,我都在Mac OS X 10.5.5上使用 osascript 运行脚本。示例调用:

osascript 'Script that takes arguments.applescript' Test argument three

我没有重定向输出,所以我知道脚本没有抛出错误。

如果我在 do shell script 上面添加显示对话框语句,它会抛出一个“不允许用户交互”错误,所以我知道它正在执行循环体。

我做错了什么?这个循环是什么导致osascript不打印任何东西?

有帮助吗?

解决方案

尝试此操作以避免使用临时文件。

to run argv
        set accumulator to do shell script "echo " & (count argv) & " arguments" altering line endings false
        repeat with i from 1 to (count argv)
                set ln to do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'" altering line endings false
                set accumulator to accumulator & ln
        end repeat
        return accumulator
end run

其他提示

您的问题似乎与循环或argv的使用无关。这是一个更简单的测试用例,只有最后的 do shell脚本实际上返回一个结果:

do shell script "echo foo"
delay 2
do shell script "echo bar"

此外,以下微小变化将产生预期结果:

to run argv
    do shell script "echo " & (count argv) & " arguments > /test.txt"

    repeat with i from 1 to (count argv)
        do shell script "echo 'Argument " & i & ": " & (item i of argv) & "' >> /test.txt"
    end repeat
end run

test.txt 将包含四行,如下所示:

3 arguments
Argument 1: foo
Argument 2: bar
Argument 3: baz

此解决方法失败:

to run argv
    do shell script "echo " & (count argv) & " arguments > /tmp/foo.txt"

    repeat with i from 1 to (count argv)
        do shell script "echo 'Argument " & i & ": " & (item i of argv) & "' >> /tmp/foo.txt"
    end repeat

    do shell script "cat /tmp/foo.txt"
    do shell script "rm /tmp/foo.txt"
end run

即使是现在,也只返回最后一行。这可能与 TN2065 的以下问题有关:

  

问:我的脚本会在很长一段时间内产生输出。如何在结果出来时阅读结果?

     

答:同样,简短的回答是你没有 - 在命令完成之前,shell脚本不会返回。在Unix术语中,它不能用于创建管道。但是,您可以执行的操作是将命令放入后台(请参阅下一个问题),将其输出发送到文件,然后在文件填满时读取该文件。

唉,我没有足够的AppleScript-fu知道如何让AppleScript本身读取多行,我怀疑它会起作用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top