You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript文件夹动作语法错误求助(HandBrake自动转码脚本)

解决AppleScript文件夹动作的「预期行尾却发现未知令牌」错误

我帮你定位了几个导致语法错误的核心问题,还有一些可以优化的细节,咱们一步步来:

错误原因分析

  • HTML实体误用:你代码里的&是HTML转义后的字符,AppleScript里字符串拼接必须用原生的&符号,这是触发语法错误的最主要原因。
  • 多余的end timeout语句:with timeout of ... seconds是on adding folder items to的修饰参数,不需要单独写end timeout来闭合,这个多余的语句直接破坏了语法结构。
  • 字符截取的写法问题:characters 1 thru -5返回的是字符列表,直接转字符串可能出现意外,换成text 1 thru -5是AppleScript里更可靠的文本截取方式。

修正后的完整代码

on adding folder items to this_folder after receiving these_items with timeout of (720 * 60) seconds
    tell application "Finder"
        -- 获取所有未标记(未处理)的MOV文件
        set targetFolder to ("Macintosh HD:Users:MacMini:Downloads:Downloaded" as alias)
        set allFiles to every file of entire contents of targetFolder whose (name extension is "mov" and label index is 0)
        
        -- 遍历所有待处理文件
        repeat with currentFile in allFiles
            try
                -- 标记为灰色,表示正在处理
                set label index of currentFile to 7
                
                -- 处理原文件路径和新文件路径(先获取未加引号的POSIX路径,再添加引号更安全)
                set origPOSIXPath to POSIX path of currentFile
                set newPOSIXPath to text 1 thru -5 of origPOSIXPath & "mp4"
                set origFilepath to quoted form of origPOSIXPath
                set newFilepath to quoted form of newPOSIXPath
                
                -- 组装并执行HandBrake转码命令
                set shellCommand to "nice /Applications/HandBrakeCLI -i " & origFilepath & " -o " & newFilepath & " --preset=\"Fast 720p30\" --optimize"
                tell current application
                    do shell script shellCommand
                end tell
                
                -- 标记为绿色,表示转码完成
                set label index of currentFile to 6
                
                -- 删除原文件(测试阶段可以先注释这部分,确认转码正常后再开启)
                set shellCommand to "rm -f " & origFilepath
                tell current application
                    do shell script shellCommand
                end tell
            on error errmsg
                -- 标记为红色,表示转码失败
                set label index of currentFile to 2
                -- 可选:打印错误信息方便调试
                display dialog "处理失败:" & errmsg
            end try
        end repeat
    end tell
end adding folder items to

额外优化说明

  1. 我把路径单独提取成targetFolder变量,后续修改路径更方便。
  2. 调整了路径处理逻辑:先获取不带引号的POSIX路径,处理后再用quoted form of添加引号,避免直接截取带引号的字符串可能出现的错误。
  3. 给错误处理部分加了display dialog,方便你调试时看到具体的错误信息。
  4. 把repeat with i from 1 to number of items改成了更简洁的repeat with currentFile in allFiles,这是AppleScript遍历列表的常用写法。

测试建议

第一次测试的时候,建议先注释掉删除原文件的代码块,确认转码功能正常、文件标记正确后,再开启删除操作,避免误删重要文件。

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:23:42