【问题标题】:applescript script runs from command line, but not when saved to app and double clickedapplescript 脚本从命令行运行,但在保存到应用程序并双击时不运行
【发布时间】:2015-08-08 23:21:51
【问题描述】:

我正在尝试编写一个脚本,该脚本既可以作为应用程序运行,也可以使用 osascript 从命令行运行。在这两种情况下,我都想弹出一个“帮助”对话框。在应用程序的情况下,它应该在我双击应用程序时弹出。在命令行启动的情况下,我希望它在我运行不带参数的脚本时弹出(例如:osascript myScript.scpt)。当我双击应用程序时,附加的脚本确实正确弹出对话框,但它确实可以从命令行工作。如果我只删除第一行的 argv ,然后删除第二行的 -- ,从而模拟 argv 的存在,双击即可正常工作。也就是说,当我使用提供的 argv 时,行为与我不使用时完全不同。这是一个错误还是我做错了什么?

on run argv             -- if I remove the argv from this line
    --  set argv to []  -- and then comment *in* this line, it works fine
    getDefaults()       -- when I double-click the app

    if (count of argv) = 0 then 
        displayHelp()  -- doesn't display on double click when I use "on run argv"
    else
        processFromCommandLine(argv)
    end if
end run

on displayHelp()
     display dialog "Help!"
end displayHelp
on processFromCommandLine(argv)
end processFromCommandLine

【问题讨论】:

    标签: applescript


    【解决方案1】:

    当您双击脚本应用程序时出错退出,因为 arg 未分配给您可以计数的类,但是您尝试获取它的计数。只需将其包装在 try 块中即可。

    on run argv
        getDefaults()
        try
            get (count of argv)
            processFromCommandLine(argv)
        on error
            displayHelp()
        end try
    end run
    

    【讨论】:

    • 使用 try 块来测试变量的存在/状态在 Applescript 中很常见。
    【解决方案2】:

    几乎可以肯定有更好的方法,但这很有效:

    on run argv
    
        -- Display help.
        if argv = current application or ¬
            argv's class ≠ list or argv's length = 0 then
            display dialog "Help!"
            return
        end if
    
        -- Do stuff.
    
    end run
    

    看起来run handlerdirect parameter 设置为...

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多