【问题标题】:AppleScript: If a file does not existAppleScript:如果文件不存在
【发布时间】:2019-07-15 12:02:59
【问题描述】:

我需要一些方法来确定某个特定文件是否存在。如果存在则执行一个脚本,如果不存在则执行另一个脚本。这是我在 applescript 中的逻辑:

If exists "File:Path:To:theFile"

tell application "Finder"
open "File:Path:To:the:script"
end tell

else

tell application "Finder"
open "File:Path:To:the:Anotherscript"
end tell

end if

唯一的问题是,有时当我使用上述逻辑时,脚本会失败,说找不到文件。我需要一个完整的证明,永远不会失败的方式来查看文件是否存在。我愿意使用终端或applescript。我敢肯定以前有人遇到过这个问题,但我在网上到处寻找答案,但找不到答案。

【问题讨论】:

    标签: applescript


    【解决方案1】:

    在您的原始代码中,您为 exists 函数提供了一个字符串,而不是一个文件,即使它是文件的路径。你必须明确地给它一个文件,否则它会像你试图做的一样对待它

    exists "god"
    

    exists "tooth fairy"
    

    exists 命令不知道你在说什么。你可以使用

    return exists alias "the:path:to:a:file" 
    

    但除非文件确实存在,否则别名不起作用,因此不存在的文件会产生错误。您当然可以捕获错误并对其进行处理,但是只给 exists 函数一个文件对象会更简单。文件对象属于 Finder 应用程序,所以:

    return exists file "the:path:to:a:file" of application "Finder"
    

    【讨论】:

      【解决方案2】:

      我使用以下来查看 Finder 中的某个项目是否存在:

      on FinderItemExists(thePath)
          try
              set thePath to thePath as alias
          on error
              return false
          end try
          return true
      end FinderItemExists
      

      我认为您缺少的是将路径转换为别名。

      【讨论】:

        【解决方案3】:

        这听起来像是try...on error block 的好地方。我相信以下应该做你想做的事:

        tell application "Finder"
           try
              open "File:Path:To:the:script"
           on error
              open "File:Path:To:the:Anotherscript"
           end try
        end tell
        

        【讨论】:

          猜你喜欢
          • 2022-12-09
          • 2013-09-18
          • 1970-01-01
          • 2014-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多