You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AppleScript中异步执行Python脚本并同步运行其他任务

解决方案

你现有代码的问题在于AppleScript的do shell script默认是同步阻塞执行的,会等待Python脚本运行完成返回结果后才会执行后续的击键逻辑,只要把Python调用改成后台异步运行,同时通过临时文件中转执行结果即可实现并行效果。

可直接运行的修改后代码

-- 先定义临时文件路径用来存储Python脚本的输出结果
set tempOutputPath to POSIX path of (path to temporary items) & "py_result.txt"

-- 后台异步启动Python脚本,结果输出到临时文件,末尾加&让进程后台运行
do shell script "python3 -c \"import time; time.sleep(60); print('finished waiting')\" > " & quoted form of tempOutputPath & " 2>&1 &"

-- 并行执行击键逻辑
repeat with i from 1 to 60
    tell application "System Events" to keystroke (i as text) & ","
    delay 1
end repeat

-- 击键完成后等待Python脚本运行结束,读取运行结果
set pyResult to do shell script "while [ ! -s " & quoted form of tempOutputPath & " ]; do sleep 0.5; done; cat " & quoted form of tempOutputPath & "; rm " & quoted form of tempOutputPath

return pyResult

实现逻辑说明

  • 调用do shell script时在命令末尾加&,会让shell命令转入后台运行,AppleScript不会等待命令完成就会立刻执行下一行代码
  • 用临时文件存储Python脚本的输出,解决异步调用无法直接获取返回值的问题
  • 所有路径都用quoted form处理,避免路径包含空格等特殊字符时执行出错
  • 如果你不需要获取Python脚本的返回结果,可以省略最后读取临时文件的步骤,击键逻辑跑完直接结束AppleScript也完全可行

内容的提问来源于stack exchange,提问作者gurkensaas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:39:03