python - 使 osascript 交互式/实时打印标准输出

标签 python terminal applescript stdout osascript

好的,我有这个非常简单的 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/

相关文章:

python - 如何在 python 中获取终端输出?

node.js - 如何终止在本地主机 :8080 that does not exist on computer 上为旧站点提供服务的 Node 进程

macos - 什么是applescript,它的用途是什么?

java - 在 Mac OSX 上从 Java 启动 AppleScript 脚本

Python ftplib.error_perm 550 : No such file or directory?

python - 使用 pandas.DataFrame.apply 查找值并将其替换为来自不同 DataFrame 的值

iphone - 在 Mac 中使用终端应用程序将 .p12 文件转换为 .pem "No such file or directory"错误?

applescript 一直工作到第一个 `end tell`

python - 在积极开发的应用程序之间共享 util 模块

python - Redis pub/sub 在订阅中添加额外的 channel