好的,我有这个非常简单的 python 脚本:
import time
import sys
for i in range(25):
time.sleep(1)
print(i)
sys.exit()
当我使用 python 运行它时(/usr/local/bin/python3.6 testscript.py
),一切正常,输出为:
1
2
3
4
etc..
每个数字都在另一个数字之后 1 秒打印。
但是当我运行时:
/usr/bin/osascript -e 'do shell script "/usr/local/bin/python3.6 testscript.py" with prompt "Sart Testing " with administrator privileges'
25秒没有任何输出,最后打印:
24
到终端。
问题是:如何让 osascript 打印出与直接运行 Python 脚本时完全相同的输出?
最佳答案
AppleScript 的 do shell script
命令在非交互式 shell 中运行,因此您无法执行 osascript
命令,正如您所拥有的那样,并期望它的输出与运行 python
相同脚本来自python
或直接运行。换句话说,直接添加 python
shebang 并使文件可执行,从而 ./testscript.py
终端 就是您所需要的。或者使用终端及其 do script
来完成此操作命令 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
代码没有shebang并且在使用终端时无法执行do script
命令:
osascript -e 'tell app "Terminal" to do script "/usr/local/bin/python3.6 /path/to/testscript.py"'
关于python - 使 osascript 交互式/实时打印标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49155168/