【问题标题】:In Applescript, Why does my "Tell app Finder" block not delete "f" even when it exists?在 Applescript 中,为什么我的“Tell app Finder”块即使存在也不会删除“f”?
【发布时间】:2017-02-06 20:50:27
【问题描述】:

这个问题类似于AppleScript set directory path in Finder,但那里的答案没有对我有用!

local destination, libraryName, f
set destination to "/Users/bryandunphy/Music/Result"
set libraryName to "Testing"
if not ((libraryName ends with ".xml") or (libraryName ends with ".XML")) then set libraryName to libraryName & ".xml"
menuClick({"iTunes", "File", "Library", "Export Library…"})
set f to "/Users/bryandunphy/Music/Result/Testing.xml" -- (destination & "/" & libraryName) as string
tell application "Finder"
    if POSIX file f exists then
        delete f
        beep
    end if
end tell
tell application "System Events" to tell process "iTunes" to tell its front window to set the value of its text field "Save As:" to libraryName
if switchDir(destination, "iTunes", true, true) then return destination & "/" & libraryName -- first true = click default (Save) button, last = create path if needed

“if switchDir”行导致“文件存在,替换?”对话框出现。

【问题讨论】:

    标签: applescript


    【解决方案1】:

    最简单的解决方案是在"System Events" 上下文中使用alias 对象

    set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
    tell alias f of application "System Events"
        if it exists then delete it
    end tell
    

    警告:这会立即删除目标文件,而不是将其移动到 trash 文件夹。
    要执行后者,请参阅下面基于Finder 的解决方案。

    "System Events" 上下文中,alias 对象可以直接使用 POSIX 路径,也可以执行文件操作。

    出于性能原因,在"System Events" 上下文而不是"Finder" 上下文中工作通常更可取,但请注意,并非某些操作只能在"Finder" 上下文中进行 - 将文件移动到垃圾箱而不是立即删除这是一个例子。


    至于为什么你的"Finder"-context 方法不起作用

    AppleScript 的方式很神秘:POSIX file f exists 确实 工作 - 它不检测文件的存在 - 但 f as POSIX file exists 可以:

    set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
    tell application "Finder"
        if f as POSIX file exists then delete f as POSIX file
    end tell
    

    另一个怪癖:带有if it exists then delete ittell f as POSIX file ... end tell 块 - 类似于上面的"System Events" 解决方案 - 工作。

    与顶部的"System Events" 解决方案不同,这是:

    • 将文件移动到回收站,而不是立即删除,
      • 这会导致系统发出将某物移至垃圾桶的声音。
    • 返回刚刚移动到回收站的 file 对象(已经在其新位置,回收站文件夹中)。

    【讨论】:

    • 在我的情况下,我正在删除文件以将其替换为自身的更新版本。因此,从用户的角度来看,文件更新没有被替换,因此系统事件是正确的选择。
    【解决方案2】:

    通过结合其他两个“相关”问题的答案,我自己找到了答案!

    “告诉块”应该替换为

    if f begins with "~" then tell application "System Events" to set f to ((home directory of current user) & items 2 through -1 of (get f))
    tell application "System Events" to if exists disk item (POSIX file f as string) then delete disk item (POSIX file f as string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 2019-07-21
      • 2021-05-02
      • 1970-01-01
      • 2021-04-05
      • 2017-11-13
      • 2020-10-25
      • 1970-01-01
      相关资源
      最近更新 更多