Добавьте количество журналов к количеству выполненных сценариев - PullRequest
0 голосов
/ 30 января 2020

Я действительно застрял. Я хочу вести журнал того, сколько раз запускается скрипт. Мой скрипт выглядит следующим образом:

set actionlist to {"action1","action2}
--select an action
set actionlist to choose from list actionlist with prompt "hello" default items {"action1"} with title "Actions"
if actionlist is {"action1"} then
    set thefile to quoted form of POSIX path of (choose file of type {"mov"})
    tell application "Terminal"

        do script "DO SCRIPT HERE"
        activate
    end tell

if actionlist is {"action2"} then
    set thefile to quoted form of POSIX path of (choose file of type {"mp4"})
    tell application "Terminal"
        do script "DO SCRIPT HERE"
        activate
    end tell

Я хочу скрипт-log.txt, который подсчитывает любое время и выполненные действия. Примерно так:

action1 = 14
action2 = 21

Возможно ли это? Спасибо за ваше время!

1 Ответ

0 голосов
/ 30 января 2020

Это выполнимо несколькими различными способами, в зависимости от ваших намерений. Проще всего было бы настроить properties следующим образом:

property action1 : 0
property action2 : 0

И затем каждый раз, когда вы выполняете действие 1 или действие 2, увеличиваете свойство:

set action1 to action1 + 1
--[...]
set action2 to action2 + 1

Интересная вещь об AppleScript Свойства заключаются в том, что они сохраняются при каждом запуске сценария, чтобы вы могли накапливать итоговые суммы за определенное время. Предостережения заключаются в том, что:

  • , если вы редактируете и перекомпилируете скрипт, свойства сбрасываются к своим начальным значениям (в данном случае 0)
  • Доступ к значениям свойств возможен только в контексте сценария, либо с помощью Display Dialog в сценарии для их отображения в предупреждении, либо путем загрузки сценария из другого сценария и косвенного чтения.

Если вы предпочитаете записывать данные в файл, вы можете использовать обработчики, как показано ниже:

... Следующее редактируется значительно для запросов в комментариях ...

property tracking_file : POSIX path of (path to home folder from user domain) & "script-log.txt"
property boundary_text : "--- Log ---"
property colon_delim : " : "
property actions_list : {"action1", "action2", "action3"}

tell application "System Events"
    if not (exists file tracking_file) then my initialize()
end tell

set chosen_action to choose from list actions_list with prompt "hello" default items {"action1"} with title "Actions"
if chosen_action is not false then
    writeToFile(chosen_action as text)
end if

on writeToFile(chosen_action)
    set file_pointer to openFilePointer()
    set tally_text to read file_pointer until boundary_text

    set action_label to chosen_action & colon_delim
    set tally_offest to (offset of action_label in tally_text) + (length of action_label)
    set current_action_tally to (text tally_offest through (tally_offest + 3) of tally_text) as integer
    set new_action_tally to zeroPad(current_action_tally + 1)
    write new_action_tally to file_pointer starting at tally_offest for 3
    write action_label & short date string of (current date) & " " & time string of (current date) & return to file_pointer starting at (get eof file_pointer) + 1
    close access file_pointer
end writeToFile

on zeroPad(a_num)
    return text -3 through -1 of ("0000" & a_num as string)
end zeroPad

on initialize()
    set intital_text to ""
    repeat with this_item in actions_list
        set intital_text to intital_text & this_item & colon_delim & "000" & return
    end repeat
    set intital_text to intital_text & return & boundary_text & return
    set file_pointer to openFilePointer()
    write intital_text to file_pointer
    close access file_pointer
end initialize

on openFilePointer()
    try
        set file_pointer to open for access tracking_file with write permission
    on error err_str number err_num
        display alert "Error " & err_num & ": " & err_str
        close access tracking_file
        set file_pointer to open for access tracking_file with write permission
    end try
    return file_pointer
end openFilePointer
...