Czy AppleScript może głęboko szukać największego pliku znajdującego się poniżej folderu?


1

Muszę stworzyć AppleScript, który znalazłby największy plik w wybranym katalogu (nawet jeśli jest w innym folderze) i wyświetlał pełną ścieżkę na ekranie.

Oto, co mam do tej pory, ale to nie działa:

set theItem to quoted form of POSIX path of (choose folder)

set theSize to (do shell script "/usr/bin/mdls -name kMDItemFSSize -raw " & theItem)

on open f

set filePath to do shell script "dirname " & POSIX path of f as string

display dialog theFilePath

Nie jestem pewien, jak powiedzieć, co nie działa z powyższego skryptu. Czy możesz pomóc w następnym kroku, aby to zadziałało?

Odpowiedzi:


2

Istnieją różne metody wykonania tego zadania, każda z zaletami i wadami. Metody powłoki są przewijanie do owski , ale nie zawsze zwracają się do aktualnych informacji . Interfejs Findera AppleScript nie jest tak wolny, jak się spodziewałem, ale zwraca tylko realne wartości dla rozmiarów plików, które zostały buforowane, w przeciwnym razie „brak wartości” dla reszty. Zdarzenia systemowe to zwykle wybrana aplikacja do zarządzania plikami AppleScript, ponieważ jest szybka po pobraniu, ale spowalnia dostęp do atrybutów plików. Nie może również wykonywać głębokiego wyliczania katalogów, takiego jak Finder (chociaż można go zaimplementować ręcznie).

Zdecydowałem się użyć mostka skryptowego Objective-C do napisania AppleScript, który jest zarówno super szybki, jak i w pełni zdolny do zejścia do podfolderów katalogu. Ogólnie rzecz biorąc, jest to najlepsza metoda, ale ma tę wadę, że nauczyciel może być nieco podejrzliwy.

# Loads the Foundation framework into the script so that we can access its
# methods and constants
use framework "Foundation"

# Declare properties that belong to the Foundation framework for easier
# referencing within the script
property this : a reference to current application
property NSArray : a reference to NSArray of this
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to 4
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to 2
property NSFileManager : a reference to NSFileManager of this
property NSSortDescriptor : a reference to NSSortDescriptor of this
property NSString : a reference to NSString of this
property NSURL : a reference to NSURL of this
property NSURLFileSizeKey : a reference to NSURLFileSizeKey of this
property NSURLNameKey : a reference to NSURLNameKey of this
property NSURLPathKey : a reference to NSURLPathKey of this

# Call the handler defined below.  This is where the script does the actual
# retrieving of the files and filesizes
get my contentsOfDirectory:"~/Downloads"

# If we stopped the script at the line above, you'd see the entire contents of 
# the directory subtree listed with file paths and filesizes, ordered in 
# descending order by filesize.  However, you only want the largest file, so
# we pick out the first item in the list.
return item 1 of the result

--------------------------------------------------------------------------------
# This is an AppleScript handler declaration
on contentsOfDirectory:dir
    local dir # This tells the handler that the variable passed as the
    # parameter is limited in scope to this handler

    # Obtain a reference to the default file manager of the filesystem
    set FileManager to NSFileManager's defaultManager()

    # This is where retrieve the contents of the directory, recursing
    # into any subfolders.  The options declared tell the method to skip
    # hidden files and not to look inside file packages, such as 
    # applications or library files.  I've declared a list of keys that
    # pre-fetch file attributes during this retrieval, making it faster
    # to access their data later: filename, full path, and file size.
    set fs to FileManager's enumeratorAtURL:(NSURL's ¬
        fileURLWithPath:((NSString's stringWithString:dir)'s ¬
            stringByStandardizingPath())) ¬
        includingPropertiesForKeys:[¬
        NSURLPathKey, ¬
        NSURLNameKey, ¬
        NSURLFileSizeKey] ¬
        options:(NSDirectoryEnumerationSkipsHiddenFiles + ¬
        NSDirectoryEnumerationSkipsPackageDescendants) ¬
        errorHandler:(missing value)

    # I created the script object just to speed up the process of
    # appending new items to the empty list it contains.
    script |files|
        property list : {}
    end script

    # This is the repeat loop that we use to enumerate the contents
    # of the directory tree that we retrieved above
    repeat
        # This allows us to access each item in the enumerator one
        # by one.
        set f to fs's nextObject()

        # Once the list has been exhausted, the value returned above
        # will be a "missing value", signifying that there are no more
        # files to enumerate.  Therefore, we can exit the loop.
        if f = missing value then exit repeat

        # Here, we retrieve the values of file attributes denoted
        # by the keys I declared earlier.  I'm picking out the path
        # and the filesize as per your needs.
        f's resourceValuesForKeys:[NSURLPathKey, NSURLFileSizeKey] ¬
            |error|:(missing value)

        # The above command returns a record containing the two
        # file attributes.  This record gets appended to the list
        # stored in the script object above.
        set end of list of |files| to the result as record
    end repeat

    # The list in the script object is an AppleScript list object.  For
    # the next part, I need a cocoa list object (NSArray).
    set L to item 1 of (NSArray's arrayWithObject:(list of |files|))

    # This defines a sort descriptor which is used to sort the array.
    # I'm telling it to use the filesize key to sort the array by 
    # filesize, which will let us grab the largest file easily.
    set descriptor to NSSortDescriptor's alloc()'s ¬
        initWithKey:"NSURLFileSizeKey" ascending:no

    # Sort the list.
    L's sortedArrayUsingDescriptors:[descriptor]

    # Return the result.
    result as list
end contentsOfDirectory:

1

To jest jako alternatywa do AppleScript Cel C kodu zastosowanego w innej odpowiedzi i jest bardziej wzdłuż linii w standardzie AppleScript kodu, pokazanych w PO. Zwróć uwagę, że podziękowania za tę odpowiedź należą do autora drugiej odpowiedzi, CJK, ponieważ pochodzi ona z usuniętych komentarzy, które zrobiliśmy sobie nawzajem pod jego pierwotną odpowiedzią. Poza tym uważam, że jego odpowiedź, pomimo złożoności, jest lepsza pod względem wydajności niż to, co jest tutaj oferowane.

Po uruchomieniu tego skryptu użytkownik wybiera folder, a wynik końcowy, nazwa największej ścieżki do pliku w wybranym folderze, w tym jego podfolderów, jest wyświetlana w oknie dialogowym.

Przykładowy kod AppleScript :

set chosenFolder to quoted form of POSIX path of ¬
    (text items 1 thru -2 of ((choose folder) as text) as text)

set theLargestFilePathname to ¬
    (do shell script "find " & chosenFolder & ¬
        " -type f -ls | sort -nrk7 | awk '{for(i=11; i<=NF; ++i) printf $i\"\"FS; exit}'")

display dialog "The largest file within the chosen folder, and its subfolders, is:" & ¬
    linefeed & linefeed & theLargestFilePathname buttons {"OK"} default button 1 ¬
    -- giving up after 3        # Remove the '--' at the front of this line to enable this.

Końcowym rezultatem mojego folderu Pobrane jest okno dialogowe pokazane poniżej:

wyświetlić okno dialogowe

Wyświetlona nazwa pliku ścieżki jest w tej chwili największym plikiem w moim folderze Pobrane o wielkości 5,27 GB na dysku.


Uwaga: Przykładowy kod AppleScript jest właśnie taki i nie zawiera żadnej obsługi błędów, która może być odpowiednia. Na użytkowniku spoczywa obowiązek dodania obsługi błędów, które mogą być odpowiednie, potrzebne lub pożądane.


@CJK, dodałem tę odpowiedź w oparciu o częściowo usunięte komentarze z Twojej odpowiedzi.
user3439894,

1
I myślę, że zasługuje na +1.
CJK
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.