Make osascript print stdout interactively / in real-time

荒凉一梦 提交于 2019-12-24 14:13:45

问题


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?


回答1:


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"'


来源:https://stackoverflow.com/questions/49155168/make-osascript-print-stdout-interactively-in-real-time

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