AppleScript代码处理大批次文件时运行失败问题求助
AppleScript大文件量执行失败问题修复方案
问题根因
- 路径拼接存在隐性错误:
POSIX path of checkfolder拼接文件名时未强制保证文件夹路径末尾带/,小样本量下可能刚好路径符合预期,大样本量下大概率出现路径错误无法匹配文件 - 单文件循环调用
do shell script开销过大:5000次重复创建shell进程会带来极大的性能损耗,还可能触发系统进程数限制 - 异常被空
try完全吞掉:没有任何错误日志输出,无法定位具体失败原因 - 冗余延迟拖慢执行:每个循环加0.1秒延迟,5000个文件单延迟就占用500秒,容易引发超时或执行异常
- 变量类型不规范:计数变量
noitem初始化为字符串类型,虽然AppleScript支持自动隐式转换,但大数值运算时可能出现异常 - 逻辑描述不一致:使用
mv命令是移动文件,最终弹窗却提示「文件已复制」,容易产生误解
修复后代码
set filenamelist to choose file with prompt "请选择要处理的csv文件名清单:" of type {"csv"} set checkfolder to POSIX path of (choose folder with prompt "选择源文件夹") -- 强制保证源文件夹路径末尾带斜杠 if checkfolder does not end with "/" then set checkfolder to checkfolder & "/" set destinationfolder to POSIX path of (choose folder with prompt "选择目标文件夹") set listOfbarcods to {} set listtttt to paragraphs of (read filenamelist as «class utf8») repeat with nextLine in listtttt if length of nextLine is greater than 0 then set nextLine1 to text 2 thru -2 of nextLine copy quoted form of (checkfolder & nextLine1 & ".pdf") to the end of listOfbarcods end if end repeat set successCount to 0 set failCount to 0 with timeout of 3600 seconds -- 一次性拼接所有文件路径,单次调用shell完成移动,大幅降低开销 set shellCommand to "mv " & (join of listOfbarcods by space) & " " & quoted form of destinationfolder try do shell script shellCommand set successCount to count of listOfbarcods on error errMsg -- 出错时可取消下方注释输出错误信息排查问题 -- display dialog errMsg set failCount to count of listOfbarcods end try end timeout display dialog "处理完成:成功移动" & successCount & "个文件,失败" & failCount & "个" as text -- 新增列表拼接辅助函数 on join of lst by delimiter set AppleScript's text item delimiters to delimiter set joinedText to lst as text set AppleScript's text item delimiters to "" return joinedText end join
优化说明
- 如需保留源文件,把代码中的
mv命令替换为cp即可实现复制逻辑 - 文件量超过1万的场景,建议直接用shell脚本完成全流程,执行效率远高于AppleScript
- 批量执行报错时可打开错误日志输出,快速定位路径、权限类问题
内容的提问来源于stack exchange,提问作者Moeen
相关产品推荐
相关产品推荐

