等待 do shell 脚本完成 [英] Waiting for do shell script to finish

查看:37
本文介绍了等待 do shell 脚本完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Applescript 在 Xcode 中创建一个应用程序来转换 PDF.

I'm trying to create an app in Xcode using Applescript to convert PDF's.

问题是我需要 Xcode/AppleScript 来等待每个do shell script"命令在开始下一个命令之前完成处理.

The problem is that I need Xcode/AppleScript to wait for each 'do shell script' command to finish processing before it starts the next.

有没有办法检测每个脚本是否已完成?

Is there a way of detecting that each script has finished?

例如

tell application "System Events"
        do shell script "/opt/local/bin/convert task1.tif output1.pdf"
    end tell

tell application "System Events"
        do shell script "/opt/local/bin/convert task2.tif output2.pdf"
    end tell

谢谢,安东尼

推荐答案

首先,从系统事件"代码块中删除执行 shell 脚本"行.do shell script"命令不需要系统事件.

First, remove your "do shell script" lines from the "System Events" blocks of code. System Events is not needed for the "do shell script" command.

接下来,您可以强制 applescript 不等待 shell 命令完成,并在 applescript 中获取命令的 PID(进程 ID).例如,运行此命令.

Next, you can force applescript to not wait for a shell command to finish and also get the PID (process id) of the command back in applescript. For example, run this command.

do shell script "/bin/sleep 5"

您将看到这是一个基本的 5 秒延迟命令,applescript 将等待这 5 秒,然后将控制权返回给脚本.

You will see that it is a basic 5 second delay command and applescript will wait those 5 seconds before returning control to the script.

现在运行这个命令.

do shell script "/bin/sleep 5 > /dev/null 2>&1 & echo $!"

您将看到现在applescript 不会等待5 秒,并且您还获得了正在运行的sleep 命令的PID.请注意我们添加到原始命令末尾的内容以实现这一目标.

You will see that now applescript doesn't wait 5 seconds and you also get the PID of the running sleep command. Notice the stuff we added to the end of the original command to make that happen.

我们可以使用这个PID.我们可以重复循环并使用ps"命令检查PID是否仍在运行.当 sleep 命令完成时,PID 将不再存在,我们可以使用它作为触发器来了解 sleep 命令何时完成.

We can use this PID. We can make a repeat loop and check if the PID is still running using the "ps" command. When the sleep command finishes the PID will no longer exist and we can use that as a trigger to know when the sleep command has finished.

set thePID to do shell script "/bin/sleep 5 > /dev/null 2>&1 & echo $!"

repeat
    do shell script "ps ax | grep " & thePID & " | grep -v grep | awk '{ print $1 }'"
    if result is "" then exit repeat
    delay 0.2
end repeat

return "the process is complete!"

所以这应该为您提供实现目标的工具.祝你好运.

So that should give you the tools to accomplish your goal. Good luck.

这篇关于等待 do shell 脚本完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆