【问题标题】:Can I force applescript to run synchronously?我可以强制applescript同步运行吗?
【发布时间】:2017-10-24 21:09:53
【问题描述】:

我正在为 iTerm2 编写一个简单的 applescript 脚本,该脚本会生成一堆选项卡并开始在其中运行服务(我有很多微服务,并且都需要运行以在本地进行测试)。

事情大部分都在工作,但是我遇到了一些稍微奇怪的行为,我认为这与 applescript 提前发送命令有关。我们来看一个具体的例子:

create tab with default profile   
tell the current session
  write text "cd services/myservice"
  write text "make build-docker"
  write text "make run-docker"
end tell

理论上,这个块应该

1) 创建一个新标签 2) 切换到新目录 3)构建一个泊坞窗图像和 4) 运行该 docker 镜像。

这偶尔会起作用,但更常见的是我在第 4 步遇到问题。具体来说,我会检查选项卡,发现“make build-docker”是最后一次运行的命令。这个命令需要一些时间,所以我假设在构建运行时发送“make run-docker”并被忽略。有没有办法强制 applescript/iTerm2 等待该命令完成以便正确执行运行?

希望这很清楚。感谢阅读!

【问题讨论】:

    标签: docker scripting applescript iterm2


    【解决方案1】:

    如果您启用了 iTerm 的 shell 集成,您可以轮询 is at shell prompt 以确定命令是否已完成:

    tell application "iTerm2"
      tell current window
        create tab with profile "BentoBox"
        tell current session
            write text "sleep 5"
            repeat while not (is at shell prompt)
               delay 0.5
           end repeat
           write text "sleep 5"
        end tell
      end tell
    end tell
    

    否则,您将需要将所有命令串在一起:

    write text "cd services/myservice; make build-docker; etc; etc; etc.."
    

    或者将它们放在 shell 脚本中并执行:

    write text "my_super_duper_shell_script.sh"
    

    或者使用 AppleScript 将 cmds 写入 tmp 文件并执行:

    回复:How can I create or replace a file using Applescript?

    【讨论】:

    • 另外请注意,bash 默认会忽略错误,除非您明确告诉它不要这样做。使用write text "cd services/myservice && make build-docker && etc && etc && etc.." 确保每个shell 命令仅在前一个命令成功时执行。或者,如果您要保存为 .sh 文件,请在顶部添加 set -e 命令,以告知 bash 在任何命令失败时中止脚本。
    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2019-08-19
    • 2014-02-06
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多