applescript 脚本从命令行运行,但在保存到应用程序并双击时不会运行

applescript script runs from command line, but not when saved to app and double clicked

我正在尝试编写一个脚本,运行既可以作为应用程序,也可以使用 osascript 从命令行编写。在这两种情况下,我都想弹出一个 "help" 对话框。对于应用程序,当我双击该应用程序时它应该会弹出。在命令行启动的情况下,我希望它在我 运行 没有参数的脚本(例如: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

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

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

几乎肯定有更好的方法,但这个方法有效:

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 似乎设置为...