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

MacOS使用osascript从Terminal向应用发送按键报错如何解决

问题原因
  • keystroke 是**System Events(系统事件)**提供的模拟按键输入接口,不属于TextEdit自身支持的AppleScript命令集。直接向TextEdit发送keystroke指令时,应用无法识别该命令,因此抛出 -1728 错误。
  • 模拟按键输入还需要目标应用处于前台激活状态,否则输入内容不会落到TextEdit的编辑区域。
解决方法

你可以根据需求选择以下两种方案:

方案1:模拟手动输入(按当前光标位置插入内容)

先激活TextEdit到前台,再调用System Events执行按键输入,命令如下:

osascript -e 'tell application "TextEdit" to activate' -e 'tell application "System Events" to keystroke "hello"'

该方案效果和手动敲入内容完全一致,支持在当前光标位置插入,但依赖TextEdit处于前台,可能被系统弹窗、其他应用打断。

方案2:直接操作文档内容(更稳定)

不需要将TextEdit切到前台,直接修改文档的文本属性,命令如下:

给当前最前面的TextEdit文档追加内容

osascript -e 'tell application "TextEdit" to set text of front document to text of front document & "hello"'

新建TextEdit文档并写入内容

osascript -e 'tell application "TextEdit" to make new document with properties {text:"hello"}'

该方案不会受前台应用切换影响,执行成功率更高,但不会触发输入相关的系统特性(如自动纠错、输入快捷键响应等)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:48:02