AppleScript 递归处理文件夹中的文件

发布于 2024-09-26 14:41:00 字数 1304 浏览 5 评论 0原文

我有一个根文件夹,里面有子文件夹。一般只有一层,但也可以更深。这些文件夹将包含不同的文件,包括一些 .rar 文件。我想创建一个遍历文件夹的递归函数,检查文件是否是 rar 文件并打开/解压它。该代码可以正常工作到第一级,没有任何问题。但递归调用不起作用,苹果脚本的错误处理很糟糕。这是我到目前为止所做的代码。

set folderName to "Macintosh HD:Users:Teja:Desktop:Madhu Babu:"

process_folder("", folderName)

on process_folder(root, folderNameToProcess)
    set fileExt to {".rar"}
    tell application "Finder"
        set theItems to every file of folder (root & folderNameToProcess)
        repeat with theFile in theItems
            copy name of theFile as string to FileName
            repeat with ext in fileExt
                if FileName ends with ext then
                    open theFile
                    delete theFile
                end if
            end repeat
        end repeat
        set theFolders to name of folders of folder (root & folderNameToProcess)
        repeat with theFolder in theFolders
            copy theFolder as string to TheFolderName
            display dialog (folderNameToProcess & TheFolderName & ":")
            try
                process_folder(folderNameToProcess, TheFolderName & ":")
            on error errStr number errorNumber
                display dialog errStr
            end try
        end repeat
    end tell
end process_folder

I have a root folder and there are sub folders in it. It is generally one level only but it can be deeper. These folders will have different files including some .rar files. I want to create a recursive function which traverses the folders, check if the file is a rar file and open/extract it. The code is working to first level with out any problem. But the recursive call is not working and apple script's error handling is horrible. Here is the code which I have done so far.

set folderName to "Macintosh HD:Users:Teja:Desktop:Madhu Babu:"

process_folder("", folderName)

on process_folder(root, folderNameToProcess)
    set fileExt to {".rar"}
    tell application "Finder"
        set theItems to every file of folder (root & folderNameToProcess)
        repeat with theFile in theItems
            copy name of theFile as string to FileName
            repeat with ext in fileExt
                if FileName ends with ext then
                    open theFile
                    delete theFile
                end if
            end repeat
        end repeat
        set theFolders to name of folders of folder (root & folderNameToProcess)
        repeat with theFolder in theFolders
            copy theFolder as string to TheFolderName
            display dialog (folderNameToProcess & TheFolderName & ":")
            try
                process_folder(folderNameToProcess, TheFolderName & ":")
            on error errStr number errorNumber
                display dialog errStr
            end try
        end repeat
    end tell
end process_folder

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦归所梦 2024-10-03 14:41:00

问题是您尝试从 Tell 块内进行递归。您的脚本正在尝试调用“Finder”中的“process_folder”,这当然不存在。

修复方法非常简单,

在对 process_folder 的递归调用前面加上“my”:

my process_folder(folderNameToProcess, TheFolderName & ":")

这将导致应用程序在您自己的范围内查找“process_folder”处理程序。

The problem is that you try to do recursion from within a tell block. Your script is trying to call a "process_folder" in "Finder" which of course does not exist.

The fix is very simple

prepend your recursive call to process_folder with "my":

my process_folder(folderNameToProcess, TheFolderName & ":")

That will cause the the application to look for a "process_folder" handler in your own scope.

2024-10-03 14:41:00

就像当您从旧车换成新法拉利时一样,您将通过使用我为自己编写的以下 AsObjC 脚本来了解什么是速度

-- Get the Files in Entire Contents of Folder by Extension, then Sort them (AsObjC)

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

property |⌘| : a reference to current application
property NSPredicate : a reference to NSPredicate of |⌘|
property NSFileManager : a reference to NSFileManager of |⌘|
property |NSURL| : a reference to |NSURL| of |⌘|
property NSMutableArray : a reference to NSMutableArray of |⌘|
property NSURLIsRegularFileKey : a reference to NSURLIsRegularFileKey of |⌘|
property NSSortDescriptor : a reference to NSSortDescriptor of |⌘|
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to 2
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to 4

set sourceFolder to POSIX path of (path to desktop folder) & "Madhu Babu"
set sourceURL to |NSURL|'s URLWithString:sourceFolder

set fileManager to NSFileManager's |defaultManager|()
set fileKey to NSURLIsRegularFileKey
set searchOptions to (NSDirectoryEnumerationSkipsPackageDescendants) + (NSDirectoryEnumerationSkipsHiddenFiles)

-- Get entire contents of folder, includung contents of subfolders, without packages and hidden files
set entireContents to (fileManager's enumeratorAtURL:(sourceURL) includingPropertiesForKeys:({fileKey}) options:(searchOptions) errorHandler:(missing value))'s allObjects()

-- Filter case-insensitively for items with "rar" extensions.
set thePredicate to NSPredicate's predicateWithFormat:("pathExtension ==[c] 'rar'")
set urlArray to entireContents's filteredArrayUsingPredicate:(thePredicate)

-- The result is probably just the files we want, but check for any folders among them while getting their paths.
set theFiles to NSMutableArray's new()
set AsObjCTrue to current application's NSNumber's numberWithBool:true
repeat with theURL in urlArray
    if ((theURL's getResourceValue:(reference) forKey:(fileKey) |error|:(missing value))'s end) is AsObjCTrue then
        tell theFiles to addObject:(theURL)
    end if
end repeat

-- Sort the remaining URLs on their paths.
set sortDescriptor to NSSortDescriptor's sortDescriptorWithKey:("path") ascending:(true) selector:("localizedStandardCompare:")
theFiles's sortUsingDescriptors:({sortDescriptor})

set theFiles to theFiles as list

Just like when you switch from an old car to a new Ferrari, you will learn what speed is by using the following AsObjC script that I wrote for myself just for this task:

-- Get the Files in Entire Contents of Folder by Extension, then Sort them (AsObjC)

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

property |⌘| : a reference to current application
property NSPredicate : a reference to NSPredicate of |⌘|
property NSFileManager : a reference to NSFileManager of |⌘|
property |NSURL| : a reference to |NSURL| of |⌘|
property NSMutableArray : a reference to NSMutableArray of |⌘|
property NSURLIsRegularFileKey : a reference to NSURLIsRegularFileKey of |⌘|
property NSSortDescriptor : a reference to NSSortDescriptor of |⌘|
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to 2
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to 4

set sourceFolder to POSIX path of (path to desktop folder) & "Madhu Babu"
set sourceURL to |NSURL|'s URLWithString:sourceFolder

set fileManager to NSFileManager's |defaultManager|()
set fileKey to NSURLIsRegularFileKey
set searchOptions to (NSDirectoryEnumerationSkipsPackageDescendants) + (NSDirectoryEnumerationSkipsHiddenFiles)

-- Get entire contents of folder, includung contents of subfolders, without packages and hidden files
set entireContents to (fileManager's enumeratorAtURL:(sourceURL) includingPropertiesForKeys:({fileKey}) options:(searchOptions) errorHandler:(missing value))'s allObjects()

-- Filter case-insensitively for items with "rar" extensions.
set thePredicate to NSPredicate's predicateWithFormat:("pathExtension ==[c] 'rar'")
set urlArray to entireContents's filteredArrayUsingPredicate:(thePredicate)

-- The result is probably just the files we want, but check for any folders among them while getting their paths.
set theFiles to NSMutableArray's new()
set AsObjCTrue to current application's NSNumber's numberWithBool:true
repeat with theURL in urlArray
    if ((theURL's getResourceValue:(reference) forKey:(fileKey) |error|:(missing value))'s end) is AsObjCTrue then
        tell theFiles to addObject:(theURL)
    end if
end repeat

-- Sort the remaining URLs on their paths.
set sortDescriptor to NSSortDescriptor's sortDescriptorWithKey:("path") ascending:(true) selector:("localizedStandardCompare:")
theFiles's sortUsingDescriptors:({sortDescriptor})

set theFiles to theFiles as list
私藏温柔 2024-10-03 14:41:00

尝试更改递归调用以

try
    my process_folder(folderNameToProcess, TheFolderName & ":")
on error errStr number errorNumber
    display dialog errStr
end try

process_folder 调用之前注意 my。这使它对我有用。

Try changing your recursive call to

try
    my process_folder(folderNameToProcess, TheFolderName & ":")
on error errStr number errorNumber
    display dialog errStr
end try

Note the my before the process_folder call. This made it work for me.

飘逸的'云 2024-10-03 14:41:00

这是我得到的有效解决方案......

--find . -name "*.rar" -type f -delete

set folderToProcess to (choose folder with prompt "Choose Folder::")

tell application "Finder"
    activate
    set fileExt to {".rar"}
    set theTopFolder to (folderToProcess as alias)
    repeat with EachFile in (get every file of folder (folderToProcess as alias))
        try
            copy name of EachFile as string to FileName
            repeat with ext in fileExt
                if FileName ends with ext then
                    set result to (open EachFile)

                    --delete Eachfile
                    msg(result)
                end if
            end repeat
        end try
    end repeat
    --display dialog (theTopFolder as text)
    repeat with EachSubDir in (get every folder of folder theTopFolder)
        try
            --display dialog (EachSubDir as text)
            repeat with EachFile in (get every file of folder (EachSubDir as alias))
                try
                    copy name of EachFile as string to FileName
                    --display dialog FileName
                    --move Eachfile to theTopFolder
                    repeat with ext in fileExt
                        if FileName ends with ext then
                            --display dialog FileName
                            set result to (open EachFile)
                            --delete Eachfile
                            msg(result)
                        end if
                    end repeat
                end try
            end repeat
            --delete folder (EachSubDir as alias)
        end try
    end repeat
end tell

Here is the solution I got which is working...

--find . -name "*.rar" -type f -delete

set folderToProcess to (choose folder with prompt "Choose Folder::")

tell application "Finder"
    activate
    set fileExt to {".rar"}
    set theTopFolder to (folderToProcess as alias)
    repeat with EachFile in (get every file of folder (folderToProcess as alias))
        try
            copy name of EachFile as string to FileName
            repeat with ext in fileExt
                if FileName ends with ext then
                    set result to (open EachFile)

                    --delete Eachfile
                    msg(result)
                end if
            end repeat
        end try
    end repeat
    --display dialog (theTopFolder as text)
    repeat with EachSubDir in (get every folder of folder theTopFolder)
        try
            --display dialog (EachSubDir as text)
            repeat with EachFile in (get every file of folder (EachSubDir as alias))
                try
                    copy name of EachFile as string to FileName
                    --display dialog FileName
                    --move Eachfile to theTopFolder
                    repeat with ext in fileExt
                        if FileName ends with ext then
                            --display dialog FileName
                            set result to (open EachFile)
                            --delete Eachfile
                            msg(result)
                        end if
                    end repeat
                end try
            end repeat
            --delete folder (EachSubDir as alias)
        end try
    end repeat
end tell
因为看清所以看轻 2024-10-03 14:41:00

尝试使用 Python 来实现此目的。如果有其他工具可以完成这项工作,那么真的没有理由浪费时间编写 Applescript。

我推荐使用 Script Debugger 来调试 Applescript,因为它有很多工具可以帮助您了解实际发生的情况,但递归遍历 Applescript 中的目录非常慢,因此如果您有一棵大树,它就会陷入困境。

Try using Python for this. There is really no reason to waste time writing Applescript if there are any other tools to do the job.

I recommend Script Debugger for debugging Applescript since it has many tools for understanding what is actually happening, but recursively traversing a directory in Applescript is very slow so if you have a big tree it will bog down.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文