3

我需要一些方法来确定特定文件是否存在。如果存在则执行一个脚本,如果不存在则执行另一个脚本。这是我在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。我敢肯定有人以前遇到过这个问题,但我在网上到处寻找答案,但找不到答案。

4

3 回答 3

8

在您的原始代码中,您为 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"
于 2009-07-14T04:43:27.180 回答
4

I use the following to see if an item in the Finder exists:

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

I think what you're missing is conversion of the path to an alias.

于 2009-07-13T12:19:47.720 回答
0

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

tell application "Finder"
   try
      open "File:Path:To:the:script"
   on error
      open "File:Path:To:the:Anotherscript"
   end try
end tell
于 2009-07-11T14:50:36.770 回答