首页 > 解决方案 > 从 macOS 应用程序调用时使用“密钥代码”的 applescript 中出现错误 1002

问题描述

我正在尝试从我的 macOS 应用程序(Mojave、Xcode 10.3)运行 AppleScript。但是,当从应用程序运行 AppleScript 时,我收到此错误:

/Users/my_username/Desktop/test_apple_script.scpt: execution error: System Events got an error: osascript is not allowed to send keystrokes. (1002)

根据其他帖子,我确保我的应用程序可以控制我的计算机(系统偏好设置 > 安全和隐私 > 隐私 > 可访问性),并且它还可以控制系统事件(系统偏好设置 > 安全和隐私 > 隐私 > 自动化)。

这是我的 AppleScript:

tell application "System Events"
    key code 48 using {command down}
end tell

该脚本在脚本编辑器中运行时有效(我只需要在系统偏好设置>安全和隐私>隐私>可访问性中授予脚本编辑器访问权限)。

这是我用来从我的应用程序运行 Apple 脚本的代码(通过osascript):

let proc = Process()
proc.launchPath = "/usr/bin/env"
proc.arguments = ["/usr/bin/osascript","/Users/my_username/Desktop/test_apple_script.scpt"]
proc.launch()

当我运行一个仅显示通知的简单 AppleScript 时,此代码可以完美运行:

tell application "System Events"
    display dialog "Test"
end tell

我怎样才能让我的 AppleScript 从我的 macOS 应用程序运行,就像我在脚本编辑器中运行它一样?

编辑:对于更多上下文,这里的命令选项卡案例只是一个示例。我试图通过单击我的应用程序中的按钮来找到一种通用的方法来模拟键盘快捷键(例如,用户单击“剪切”按钮并且应用程序的行为就像用户刚刚按下了 command + x)。可能有比使用 AppleScript 更好的方法,但我知道使用 AppleScripts 可以做我想做的事情。

编辑:如果我最初的问题不清楚,显示通知的简单 AppleScript 已经在我的应用程序中运行。当我尝试运行模拟用户从键盘输入的 AppleScript 时,就会出现问题。

编辑:这里的代码暂时对我有用,但不再有效。我根本没有更改代码。我只是再次运行我的应用程序。

let PlayPauseScript = "tell application \"Spotify\"\n playpause\n end tell"\"test\"\n end tell"
if let scriptObject = NSAppleScript(source: PlayPauseScript) {
    scriptObject.executeAndReturnError(nil)
}

编辑: 这是当前问题所在。根据建议,我将其添加到我info.plist的 Spotify AppleScript 中(当通过 NSAppleScript 调用时):

<key>NSAppleEventsUsageDescription</key> 
<string>...this is why I need permission...</string>

看来我的问题(现在)只是使用系统事件的 AppleScripts。尽管确保我的应用程序和osascript都被允许控制我的计算机(通过安全和隐私>隐私>可访问性),但我现在在使用NEAppleScriptand时遇到相同的错误(1002) osascript。我的应用程序也被允许控制系统事件(安全和隐私>隐私>自动化)。错误在 Xcode中osascript打印到控制台,我NEAppleScript通过使用此代码(在按钮的 @IBAction 中)发现了错误代码:

let script =
"""
try
    tell application "System Events"
        keystroke "c" using {command down}
    end tell
on error errMsg number errorNumber
    display dialog "An unknown error occurred:  " & errorNumber as text
end try
"""

if let scriptObject = NSAppleScript(source: script) {
    scriptObject.executeAndReturnError(nil)
}

上面的代码导致它出现在对话框中: An unknown error occurred: 1002

当我的应用程序运行时,它会提示我让它控制系统事件,我总是这样做。我的应用程序没有沙盒化。我相信两者都NSAppleScript曾经oascript 我工作过,但是当我再次运行该应用程序时停止工作(尽管我没有对我的代码进行任何更改,但我几乎是肯定的)。

我不知道这是否提供信息,但我对可能发生的事情的唯一其他线索是我一直必须检查和取消选中脚本编辑器的权限security & privacy > privacy > accessibility才能让它运行这些 AppleScript,因为它告诉我脚本不允许编辑器发送击键。

标签: swiftmacospermissionsapplescriptkeystroke

解决方案


修理osascript 1002 permission issue.

转到安全和隐私 -> 隐私选项卡 -> 辅助功能 -> 添加 osascript (/usr/bin/osascript)

或使用NSAppleScript


推荐阅读