Applescript:如何使用默认程序打开文件?

时间:2012-04-12 15:22:16

标签: scripting applescript

在一个AppleScript中,我收到一个我要打开的文件路径。

文件路径采用“/Users/xxx/my/file/to/open.xyz”格式。

我想用默认程序打开它。如果它是AVI,我需要用视频程序打开它,如果它是xls,有excel,......

我尝试了几件事但没有取得任何成功:

--dstfile contains the previous path
tell application "Finder"
    activate
    open document dstfile
end tell

- >我收到错误1728,告诉我他无法获取文件

tell application "Finder"
    activate
    open document file dstfile
end tell

- >同样在这里

tell application "Finder"
    activate
    open document POSIX file dstfile
end tell

- >同样在这里

我确信该文件存在,因为我在执行此代码之前执行此操作:

if not (exists dstfile) then
    display dialog "File isn't existing"
end if

我不能使用...的synthax open.xyz,因为我收到它作为参数。

请帮助我绝望:'(

回答:根据答案,我最终得到了这个:

set command to "open " & quoted form of dsturl
do shell script command

2 个答案:

答案 0 :(得分:16)

你的问题有两个方面:

  1. 您的路径是POSIX表示法,AppleScript无法强制转换为Finder可接受的别名文件对象,因为这些只会从路径字符串中隐式创建。 HFS表示法(Users:xxx:my:file:to:open.xyz)。明确声明您的路径 POSIX文件将解决此问题。然而,
  2. 您对Finder的调用前缀文档到路径,但Finder的AppleScript字典不包含文档对象类型(有一个文档文件 object,但它是 finder item 的子元素,无法在此调用中创建)。删除该部分将解决问题。
  3. TL; DR:以下行将打开默认程序中通过POSIX路径给出的文件,而无需求助于shell:

    tell application "Finder" to open POSIX file "/Users/xxx/my/file/to/open.xyz"
    

    警告:这是最简单的解决方案,但它只适用于合格的POSIX路径(即那些以/开头的路径),就像问题中的路径一样。处理相对的(即以~...开头的路径)OTOH需要AppleScript-ObjectiveC API(并非完全无关紧要)或shell(对您的报价感兴趣)。

答案 1 :(得分:2)

尝试:

set dstfile to "~/xxx/my/file/to/open.xyz"
do shell script "open " & dstfile & ""