Home > Software design >  Run python in Applescript asynchronously
Run python in Applescript asynchronously

Time:09-26

So I want a python script to start at the beginning of my AppleScript and while it's running, I want to do some other things. Something like this:

set theResult to do shell script "python3 -c \"import time; time.sleep(60); print('finished waiting')\""

repeat with i from 1 to 60
    tell application "System Events" to keystroke (i as text) & ","
    delay 1
end repeat

return theResult 

It would of course be something more complicated than time.sleep(), that's just for demonstration purposes.

Is there a way to keystroke the numbers while the python script is "loading"?

CodePudding user response:

Here is the example, which uses osascript & redirecting result to /dev/null for similar test:

do shell script "osascript -e '
     repeat 5 times
      delay 2
   display notification \"TEST\"
    end repeat
' &> /dev/null &" -- [end shell script]

delay 1
repeat 5 times
    display notification "OTHER"
    delay 2
end repeat

Other example - with redirecting result to temp file, and returning result from it after the shell script terminating:

set tempPath to (POSIX path of (path to temporary items from user domain)) & "result.txt"

do shell script "osascript -e '
     repeat 5 times
      delay 2
   display notification \"TEST\"
    end repeat
return \"Loading finished\"
' &> " & tempPath & " &" -- [end shell script]

delay 1
repeat 5 times
    display notification "OTHER"
    delay 2
end repeat

set theResult to read (tempPath as POSIX file)

CodePudding user response:

Using the existing code from your question, albeit modified to work and using a lesser amount of time for testing, the following works:

Example AppleScript code:

do shell script "python3 -c \"import time; time.sleep(5); print('finished waiting')\" &>/tmp/result &"

repeat with i from 1 to 5
    tell application "System Events" to keystroke (i as string) & ","
    delay 1
end repeat

return (read "/tmp/result")
  • Related