AppleScript如何在代码中获得STDIN?

Sea*_*ain 4 macos applescript osx-mountain-lion

谷歌建议

echo "input" | osascript filename.scpt
Run Code Online (Sandbox Code Playgroud)

filename.scpt

set stdin to do shell script "cat"
display dialog stdin
Run Code Online (Sandbox Code Playgroud)

但是,我只能得到空白对话框:它没有文字.如何在版本中从AppleScript获取stdin?

我的操作系统版本是OSX 10.8 Mountain Lion.

phs*_*phs 6

根据这个帖子,从10.8起,AppleScript现在积极地关闭标准.通过将其滑动到未使用的文件描述符,可以保存它.这是在bash中执行此操作的示例.

在这里,我们再次使用cat魔术的子进程读取它fd.

$ echo world | osascript 3<&0 <<'APPLESCRIPT'
>   on run argv
>     set stdin to do shell script "cat 0<&3"
>     return "hello, " & stdin
>   end run
> APPLESCRIPT
hello, world
$
Run Code Online (Sandbox Code Playgroud)


jox*_*oxl 6

对不起,没有足够的声誉评论答案,但我认为有一些重要的值得指出...

在该解决方案@ regulus6633的答案一样的数据管道进入osascript.它只是将整个管道内容(在本例中为echo输出)填充到变量中,并将其作为命令行参数传递给osascript.

这个解决方案可能无法按预期工作,具体取决于你的管道中的内容(也许你的shell也扮演了一个角色?)...例如,如果那里有null(\0)字符:

$ var=$(echo -en 'ABC\0DEF')
Run Code Online (Sandbox Code Playgroud)

现在你可能认为var包含由null字符分隔的字符串"ABC"和"DEF" ,但事实并非如此.null字符消失了:

$ echo -n "$var" | wc -c
    6
Run Code Online (Sandbox Code Playgroud)

但是,使用@ phs的答案(真正的管道),你得到零:

$ echo -en 'ABC\0DEF' | osascript 3<&0 <<EOF
>   on run argv
>     return length of (do shell script "cat 0<&3")
>   end run
>EOF
7
Run Code Online (Sandbox Code Playgroud)

但那只是使用了零.尝试将一些随机二进制数据osascript作为命令行参数传递:

$ var=$(head -c8 /dev/random)
$ osascript - "$var" <<EOF
>   on run argv
>     return length of (item 1 of argv)
>   end run
>EOF
execution error: Can’t make some data into the expected type. (-1700)
Run Code Online (Sandbox Code Playgroud)

再次,@ phs的答案将处理这个罚款:

$ head -c8 /dev/random | osascript 3<&0 <<EOF
>  on run argv
>    return length of (do shell script "cat 0<&3")
>  end run
>EOF
8
Run Code Online (Sandbox Code Playgroud)


reg*_*633 4

我知道“设置 stdin 来执行 shell 脚本“cat””曾经有效。但我无法让它在 10.8 中工作,而且我不确定它什么时候停止工作。无论如何,您基本上需要将 echo 命令输出获取到一个变量中,然后该变量可以用作 osascript 命令中的参数。你的 applescript 也需要处理参数(在运行 argv 时)。最后,当您使用 osascript 时,您必须告诉应用程序“显示对话框”,否则会出错。

综上所述,这是一个处理参数的简单苹果脚本。将此设置为 filename.scpt 的代码。

on run argv
    repeat with i from 1 to count of argv
        tell application "Finder"
            activate
            display dialog (item i of argv)
        end tell
    end repeat
end run
Run Code Online (Sandbox Code Playgroud)

这是要运行的 shell 命令...

var=$(echo "sending some text to an applescript"); osascript ~/Desktop/filename.scpt "$var"
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。祝你好运。