Waiting for do shell script to finish

只愿长相守 提交于 2021-02-06 12:51:40

问题


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

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?

e.g.

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

Thanks, Anthony


回答1:


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.

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"

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.

Now run this command.

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

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.

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.



来源:https://stackoverflow.com/questions/20146093/waiting-for-do-shell-script-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!