【问题标题】:How to tell an Applescript to stop executing如何告诉 Applescript 停止执行
【发布时间】:2018-03-15 06:23:42
【问题描述】:

Applescript 的“从列表中选择”用户交互有一个“取消”按钮——我希望这个“取消”告诉脚本立即停止执行。换句话说:

 set wmColor to choose from list {"Black", "Black for all", "White", 
     "White for all"} with prompt "What color should the watermark be?" 
     default items "White for all" without multiple selections allowed and 
     empty selection allowed
 if wmColor is false
     *tell script to stop executing*
 end if

似乎找不到怎么做——有人知道怎么做吗?

【问题讨论】:

    标签: applescript


    【解决方案1】:

    错误号 -128 是“用户取消”,并将停止脚本 - 例如:

    if wmColor is false then
        error number -128
    end if
    

    【讨论】:

    • 这只有在没有包含在捕获此类错误的 try 块中时才有效。
    • JXA 变体:const e = new Error("User canceled."); e.errorNumber = -128; throw e;。魔术:JS Error 类没有定义 errorNumber 属性,但您必须将 errorNumber 设置为 -128 以避免向用户显示错误对话框。
    【解决方案2】:

    “return”告诉脚本停止执行:

    display dialog "Do you want to exit this script?" with icon note buttons {"Exit", "Continue"}
    if the button returned of the result is "Exit" then
      return
    end if
    

    【讨论】:

    • 您能否详细说明您的答案,添加更多关于您提供的解决方案的描述?
    • 在我看来,要以正常方式停止执行脚本,使用return 比抛出用户异常更好选项。
    • 嗯,不是真的 - 它告诉当前处理程序返回(没有值)。如果你在你的脚本的顶层,那很好,它会结束执行,但是如果你在一个处理程序中,它会返回一个 nil 给任何调用它的脚本,并且脚本会愉快地继续执行(可能出乎意料如果调用者不期望缺失值,则结果)。
    • 这只是在我使用它时结束了if 语句,而不是退出脚本。 error 方法更好。
    • 我只想更改此代码,使其变成一行:if wmColor is false then return
    【解决方案3】:

    对于通过 osascript 调用的 AppleScript 的特定情况,可以通过以下方式终止它,向 shell 返回状态 0:

    tell me to "exit"
    

    终止,发出消息并返回状态 1,方法是:

    tell me to error "{your message}"
    

    上面写了这样一行到标准错误:

    {scriptname}: execution error: {your message} (-2700)
    

    这是一个替换神秘的“-2700”的示例,并且可能符合 jefflovejapan 的要求:

    tell me to error "Terminated by user" number 0
    

    将其写入标准错误:

    {scriptname}: execution error: Terminated by user (0)
    

    并返回状态 1。

    我通过实验了解到这一点,阅读后: AppleScript Language Guide - error Statements

    【讨论】:

      【解决方案4】:

      我发现这对于在应用程序(例如,InDesign CS5.5)中运行的脚本非常有效:

      repeat 100 times
          tell application ("System Events") to keystroke "." using command down
          delay (random number from 0.5 to 5)
      end repeat
      

      这是从 answer 修改而来的。

      【讨论】:

        【解决方案5】:

        您可以使用“退出”一词退出当前应用程序。如果您将脚本保存为应用程序,则可以使用它。

        if wmColor is false
            quit
        end if
        

        【讨论】:

        • 请注意,如果您在脚本编辑器中运行的脚本上使用退出命令,它将退出脚本编辑器。
        • "quit" 如果您处于告诉应用程序“Finder”块中,则不起作用。
        • 它正在退出运行中的自动机,并在使用它时在终端中显示错误Couldn’t communicate with a helper application.
        猜你喜欢
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        • 2015-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多