Waiting for do shell script to finish

前端 未结 1 1749
一整个雨季
一整个雨季 2021-02-10 01:51

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 f

相关标签:
1条回答
  • 2021-02-10 02:47

    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.

    0 讨论(0)
提交回复
热议问题