使 osascript 以交互方式/实时方式打印标准输出 [英] Make osascript print stdout interactively / in real-time
问题描述
好的,我有一个非常简单的 python 脚本:
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()
当我使用 python 运行它时 (/usr/local/bin/python3.6 testscript.py
),一切正常,输出如下:
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..
每个数字在另一个之后打印 1 秒.
With each number printed 1 second after the other.
但是当我跑步时:
/usr/bin/osascript -e 'do shell script "/usr/local/bin/python3.6 testscript.py" with prompt "Sart Testing " with administrator privileges'
25 秒内没有任何输出,最后打印:
There isn't any output for 25 seconds and finally it prints:
24
到终端.
问题是:如何让 osascript 打印出与直接运行 Python 脚本时完全相同的输出?
The question is: How can I make osascript print the exact same output as when I run the Python script directly?
推荐答案
AppleScript's do shell script
command 在非交互式 shell 中运行,所以你不能像你拥有的那样执行 osascript
command 并期望它输出与运行 python
script相同的输出em> 通过 python
或直接运行.换句话说,直接添加 python
shebang 并使文件可执行,因此 ./testscript.py
在 终端强> 就是你所需要的.或者用 终端 和它的 do script
command 和 osascript
来做.
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
.
将python
代码另存为.例如:
#!/usr/local/bin/python3.6
import time
import sys
for i in range(25):
time.sleep(1)
print(i)
sys.exit()
使其可执行:
chmod u+x testscript.py
在终端中运行:
./testscript.py
或者:
osascript -e 'tell app "Terminal" to do script "/path/to/testscript.py"'
或者 python
code 没有 shebang 并且在使用 Terminal 的 do 脚本时不能执行
命令:
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"'
这篇关于使 osascript 以交互方式/实时方式打印标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!