获取子文件夹父级的路径:Applescript

获取子文件夹父级的路径:Applescript

当我将文件夹放到用 Applescript 编码的应用程序上时,我想获取子文件夹的父文件夹的路径

因此,如果我将一个名为“Test1”的文件夹放在桌面上

我希望脚本将“/Users/username/Desktop/”作为“Test1”的父路径。这是我的代码:

on open the_dropped_folder

tell application "Finder"

 set FolderPath to the_dropped_folder
 set ParentPath to container of FolderPath
 set thepath to POSIX path of ParentPath

end tell
end open

这将引发错误,指出:

“无法获取 {alias “Mac HD: Users:username:Desktop:Test1:”} 的类 ctnr

知道如何实现这个吗?

答案1

open处理程序的参数得到一个列表对象1。错误消息中的花括号 ( alias)表示在尝试操作列表对象时发生了错误。{}

因此,您需要使用类似于set FolderPath to first item of the_dropped_folder处理单个项目而不是列表的方法(并且可能在您使用它时为参数指定复数名称,以便“阅读起来更好”)。这应该可以让您的set ParentPath to container of FolderPath语句正常工作。

下一个语句可能会失败。ParentPath将是发现者 folder对象没有属性POSIX path。解决这个问题最简单的方法通常是发现者将其item对象(folder是的子类item)转换为alias对象,然后提取其POSIX pathalias对象确实具有POSIX path属性)。

如果你把所有这些放在一起,你可能会得到如下结果:

on open someDroppedAliases
    set theAlias to first item of someDroppedAliases
    tell application "Finder"
        set parentFolder to container of theAlias
        set parentFolderAlias to parentFolder as alias
    end tell
    set parentFolderPath to POSIX path of parentFolderAlias
    display dialog "Path of container:" default answer parentFolderPath
end open

没有所有中间变量:

on open someDroppedAliases
    tell application "Finder" to ¬
        set parentFolderPath to POSIX path of ¬
            (container of first item of someDroppedAliases as alias)
    display dialog "Path of container:" default answer parentFolderPath
end open

或者,系统事件(其item对象实际上具有POSIX path属性):

on open someDroppedAliases
    tell application "System Events" to ¬
        set parentFolderPath to POSIX path of ¬
            container of first item of someDroppedAliases
    display dialog "Path of container:" default answer parentFolderPath
end open

注意:我的版本(或您最初的版本)中没有任何内容是专门用于处理文件夹的。同一个程序将处理已删除的文件并生成其容器。


1 从技术上讲,它们是«class bmrk»Snow Leopard 中的对象,它们的工作方式似乎与真正的alias对象大致相同(尽管可能存在有一些差异与真实alias物体的差异)。

答案2

这里是另一个有用的例子(我只是将上述内容概括为说明什么对我这样的年轻玩家来说似乎是一个常见的陷阱;我没有意识到括号很重要)。

假设 tmpItem 是一个放在 droplet 上的文件。您可以告诉应用程序“Finder”...

将目标设置为 tmpItem 的 POSIX 路径——这将起作用

将目标设置为 tmpItem 容器的 POSIX 路径——这将失败

将目标设置为 tmpItem 容器的 POSIX 路径作为别名——这将失败

将目标设置为 POSIX 路径(tmpItem 的容器作为别名)——这将成功

相关内容