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

查看:121
本文介绍了等待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

谢谢,安东尼

推荐答案

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

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命令完成,也可以将命令的PID(进程ID)恢复为applescript.例如,运行此命令.

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天全站免登陆