使用 Applescript 旋转屏幕时出错

Error when rotating screen with Applescript

我使用以下脚本自动旋转便携式显示器。

tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell

tell application "System Events" to tell process "System Preferences" to tell window "ASUS MB16AC"
    click radio button "Display" of tab group 1
    click pop up button "Rotation:" of tab group 1
    click menu item "90°" of menu 1 of pop up button "Rotation:" of tab group 1
    set success to 0
    repeat until success is equal to 1
        delay 1
        try
            tell sheet 1
                click button "Confirm"
                set success to 1
            end tell
        on error errText
            log errText
            delay 1
        end try
    end repeat
end tell

quit application "System Preferences"

在终端上使用 osascript 调用脚本时,我收到以下错误消息,但代码仍然可以完成工作。

System Events got an error: Can’t get sheet 1 of window "ASUS MB16AC" of process "System Preferences". Invalid index.

如何避免这个错误?

-----

附加信息:

当 运行 在 Script Editor 下时,脚本工作 没有错误

只有当我使用 osascript 从终端执行脚本时才会出现错误。

在尝试单击按钮之前检查 sheet 是否存在,如下所示:

repeat until success is equal to 1
    delay 1
    if exists sheet 1 then
        try
            tell sheet 1
                click button "Confirm"
                set success to 1
            end tell
        on error errText
            log errText
            delay 1
        end try
    end if
end repeat

有了 if exists 块,您可能甚至不需要 try 块。

下面的示例 AppleScript code 是我编写代码的方式,并且有效对我来说,在 macOS High Sierra:

if running of application "System Preferences" then
    try
        tell application "System Preferences" to quit
    on error
        do shell script "killall 'System Preferences'"
    end try
end if

repeat while running of application "System Preferences" is true
    delay 0.1
end repeat

tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell

tell application "System Events" to tell process "System Preferences" to tell window 1
    click pop up button 1 of tab group 1
    click menu item 2 of menu 1 of pop up button 1 of tab group 1
    repeat until exists sheet 1
        delay 0.5
    end repeat
    click button 1 of sheet 1
    delay 0.1
end tell

tell application "System Preferences" to quit

注意:示例 AppleScript code 就是这样, sans included error 处理不包含任何额外的 error 处理可能是适当的。用户有责任根据需要或需要添加任何 错误处理 。看看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.