【问题标题】:Print to stdout from osascript/Applescript从 osascript/Applescript 打印到标准输出
【发布时间】:2021-09-16 06:04:02
【问题描述】:

我有一些 AppleScript 代码正在使用 osascript 执行。这是一个更大的 Perl 程序的一部分。我希望能够从 AppleScript 打印到标准输出,然后让 Perl 脚本处理输出。但我无法从 AppleScript 中打印。我该怎么办?

这是我尝试过的:

  • do shell script "echo Foo"。不输出 Foo。
  • This Google Groups discussion 做了一些诡计来打开 /dev/fd/1。对我来说,我收到“找不到文件 Macintosh HD:dev:fd:1”的错误

这是我正在运行的脚本:

tell application "Safari"
        set window_list to every window
        repeat with the_window in window_list
                set tab_list to every tab in the_window

                repeat with the_tab in tab_list
                        set the_url to the URL of the_tab
                        -- I'd like to put a print statement here,
                        -- instead of display dialog
                        display dialog the_url
                end repeat
        end repeat
end tell

由于osascript 会自动打印程序的最后一个值,我可以将 URL 收集到一个列表中并打印出来。但是我的 Perl 脚本必须解析列表、删除引号等。似乎每行只打印一个 URL 应该更简单。

谢谢

【问题讨论】:

  • AppleScript hello world 是终端上的这一行:osascript -e 'log "hello world!"' 应该打印:hello world! 到标准输出。您可以打印内置变量的内容,例如:log version,它会打印类似1.0 的内容。选择的标准输出取决于你用来运行它的解释器的版本(osascript)和前面几行定义的应用程序上下文,Finder、Chrome 和终端都以不同的方式重定向你的日志输出。要接收命令行参数,请使用on run argv。使用display dialog 访问屏幕。

标签: applescript


【解决方案1】:

我不知道如何做你所要求的,我不知道 Perl,但是我认为如果你将你的 url 收集在一个字符串而不是一个列表中,你可以让 perl 的解析变得简单。每个 url 将位于字符串的单独行上。 Perl 应该能够很容易地把它变成一个数组,然后用它做一些事情。类似于下面的applescript。当然,您可以在 applescript 中使用不同的分隔符。我使用了“return”,但它也可以很容易地成为“逗号”或您想要的任何其他字符。在 perl 中最容易将字符串更改为数组的方法。

set urlString to ""

tell application "Safari"
    set window_list to every window
    repeat with the_window in window_list
        set tab_list to every tab in the_window

        repeat with the_tab in tab_list
            set the_url to the URL of the_tab
            set urlString to urlString & the_url & return
        end repeat
    end repeat
end tell

return text 1 thru -2 of urlString

【讨论】:

  • 谢谢,这将使事情更容易解析。输出基本上和我打印的一样。但我将推迟接受这个作为答案,希望其他人知道如何在不建立字符串的情况下打印。
  • 为什么从 osascript 到 stdout 的唯一方法是最终返回值?
【解决方案2】:

我发现我可以使用“日志”将结果转储到 STDERR, 虽然我不得不使用 Chrome 而不是 Safari:

#!/usr/bin/osascript 告诉应用程序“Chrome” 在每个窗口中用 w 重复 在 w 的标签中重复 t 日志(获取 t 的 URL) 结束重复 结束重复 结束告诉

【讨论】:

  • 这对我来说是最好的答案,因为您可以从循环中输出到其他程序,非常适合大规模循环。
【解决方案3】:

使用log就可以了。

MacBookPro:~ zxj5470$ cat demo.scpt 
tell application "Terminal"
    set WindowNum to get window count
    log WindowNum
end tell
MacBookPro:~ zxj5470$ osascript demo.scpt 
1 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 2018-12-25
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多