如何通过 Applescript 显示默认的 Safari 下载文件夹?

How to reveal default Safari downloads folder through Applescript?

我是 AppleScript 的新手,想知道如何通过 AppleScript 在 Safari 中显示默认下载文件夹。

---我已经尝试过的---

设置文件路径以执行 shell 脚本 "defaults read com.apple.Safari DownloadsPath" 执行 shell 脚本 "open " & 引用形式的文件路径

根据我的理解,上述脚本会将变量 "filePath" 设置为 Safari 在首选项中的默认 PList 条目。 只要该位置不在用户主文件夹中的某处,这就很好用。如果它在用户文件夹中,日志会在路径前显示一个“~/”,而不会引用用户主文件夹之前的任何内容(相对路径)

我如何实现我的目标?有没有办法获取文件夹的绝对路径?或者可能是另一种方法?

这是一个使用Python的方法:

do shell script "python -c \"import os; print os.path.expanduser('`defaults read com.apple.Safari DownloadsPath`')\""

如果你真的想要长的 AppleScript 方法,试试这个:

set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
    set item 1 of filePathWords to (POSIX path of (path to home folder as string))
    set filePath to filePathWords as string
else
    set filePath to "/" & filePathWords as string
end if

如果路径中的第二个“/”困扰您(我有点困扰...),您可以改用它:

set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
    set item 1 of filePathWords to (do shell script "cd ~ && pwd")
    set filePath to filePathWords as string
else
    set filePath to "/" & filePathWords as string
end if

您可以通过 Applescript GUI 脚本执行此操作,使 Applescript 单击 'view' 菜单中的 'show downloads' 选项:

tell application "Safari"
    activate
end tell
tell application "System Events"
    tell process "Safari"
        tell menu bar 1
            tell menu bar item "view"
                tell menu "View"
                    click menu item "Show downloads"
                end tell
            end tell
        end tell
    end tell
end tell

基于@WilliamTFroggard 的回答:

tell application "Finder"
    set folderPath to do shell script "defaults read com.apple.Safari DownloadsPath"
    if folderPath = "~" or folderPath starts with "~/" then ¬
        set folderPath to text 1 thru -2 of POSIX path of (path to home folder) & rest of characters of folderPath
    open POSIX file folderPath as alias
    activate
end tell

text element 用于从主文件夹 (/Users/johndoe/) 中删除尾随 /

rest property returns folderPath~ 之后的每个字符 (~/Downloads).

/Users/johndoe + /Downloads = /Users/johndoe/Downloads.

我想你想要的是这个:

tell application "Finder"
activate
open ("/Users/yourname/Downloads" as POSIX file)
end tell

只需将 "yourname" 替换为您在 Finder 中的名字即可。