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

J4N*_*J4N 10 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
Run Code Online (Sandbox Code Playgroud)

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

tell application "Finder"
    activate
    open document file dstfile
end tell
Run Code Online (Sandbox Code Playgroud)

- >在这里相同

tell application "Finder"
    activate
    open document POSIX file dstfile
end tell
Run Code Online (Sandbox Code Playgroud)

- >在这里相同

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

if not (exists dstfile) then
    display dialog "File isn't existing"
end if
Run Code Online (Sandbox Code Playgroud)

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

请帮助我绝望:'(

:基于答案,我最终得到了这个:

set command to "open " & quoted form of dsturl
do shell script command
Run Code Online (Sandbox Code Playgroud)

kop*_*hke 17

你的问题有两个方面:

  1. 您的路径是POSIX表示法,AppleScript无法强制转换为Finder可接受的别名文件对象,因为这些只能通过HFS表示法(Users:xxx:my:file:to:open.xyz)中的路径字符串隐式创建.明确声明您的路径为POSIX文件将解决此问题.然而,
  2. 您调用Finder前缀文档到路径,但Finder的AppleScript字典不包含文档对象类型(有文档文件对象,但它是查找项的子,无法在此调用中创建).删除该部分将解决该问题.

TL; DR:以下行将打开通过默认程序中的POSIX路径给出的文件,而无需求助于shell:

tell application "Finder" to open POSIX file "/Users/xxx/my/file/to/open.xyz"
Run Code Online (Sandbox Code Playgroud)

警告:这是最简单的解决方案,但它只适用于合格的POSIX路径(即以那些开头的路径/),就像问题中的路径一样.处理相对的人(即路径开始~,...)OTOH需要要么AppleScript的API的ObjectiveC(不完全微不足道的)或壳(与你的报价乐趣).