Search code examples
pythonterminalapplescriptstdoutosascript

Make osascript print stdout interactively / in real-time


Ok, so I have this very simple python script:

import time
import sys

for i in range(25):
    time.sleep(1)
    print(i)

sys.exit()

When I use python to run it (/usr/local/bin/python3.6 testscript.py), all works fine and the output reads:

1
2
3
4
etc..

With each number printed 1 second after the other.

However when I run:

/usr/bin/osascript -e 'do shell script "/usr/local/bin/python3.6 testscript.py" with prompt "Sart Testing " with administrator privileges'

There isn't any output for 25 seconds and finally it prints:

24

To the terminal.

The question is: How can I make osascript print the exact same output as when I run the Python script directly?


Solution

  • AppleScript's do shell script command runs in a non-interactive shell, so you cannot execute the osascript command as you have it and expect it to output the same as running the python script via python or run directly. In other words, directly being adding the python shebang and making the file executable and thus ./testscript.py in Terminal is all you need. Or do it with Terminal and its do script command with osascript.

    Save the python code as. e.g.:

    #!/usr/local/bin/python3.6
    
    import time
    import sys
    
    for i in range(25):
        time.sleep(1)
        print(i)
    
    sys.exit()
    

    Make it executable:

    chmod u+x testscript.py
    

    Run it in Terminal:

    ./testscript.py
    

    Or:

    osascript -e 'tell app "Terminal" to do script "/path/to/testscript.py"'
    

    Or the python code without the shebang and not made executable while using Terminal's do script command:

    osascript -e 'tell app "Terminal" to do script "/usr/local/bin/python3.6 /path/to/testscript.py"'