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
相关产品推荐
相关产品推荐

