Как мне заставить мой скрипт обновить его результаты? - PullRequest
0 голосов
/ 20 июня 2019

Я разрабатываю программу, которая выводит системную информацию об используемом вами устройстве. Люди могут использовать эту программу, чтобы получить мгновенную статистику на своем устройстве без необходимости заходить в настройки. Я хочу добавить кнопку обновления в диалоговом окне, чтобы обновить информацию. Благодаря тому, как я это сделал, я продолжаю получать ошибки.

Я попытался добавить функцию повтора, чтобы она выполняла тот же процесс (поэтому обновляет результаты), и я попытался использовать обработчик, который также действует как функция повтора (я довольно новичок в AppleScript, поэтому я могу использовать слова неправильно).

repeat
set accessCode to "false"
repeat with i from 1 to 5
    try
        do shell script "ping -o www.google.com"
        exit repeat
    on error
        set accessCode to "true"
        if i = 5 then set conStaus to "Inactive"
    end try
end repeat
if accessCode = "true" then
    set conStatus to "Inactive"
else if accessCode = "false" then
    set conStatus to "Active"
end if
set sysinfo to system info
set computerName to computer name of sysinfo
set osVersion to system version of sysinfo
set currentUser to short user name of sysinfo
set userId to user ID of sysinfo
set ipAddress to IPv4 address of sysinfo
set localArea to user locale of sysinfo
set ethernetAddress to primary Ethernet address of sysinfo
set coreCount to (do shell script "sysctl -n hw.ncpu")
set cpuType to CPU type of sysinfo
set cpuSpeed to CPU speed of sysinfo
set physMemMeg to physical memory of sysinfo
set physMemGig to (round (physMemMeg / 1000))
tell application "Finder" to set diskName to name of startup disk
tell application "Finder" to set freeBytes to free space of disk diskName
set freeBytesGigs to (freeBytes / (1024 * 1024 * 0.1024) div 100) / 100
set macModel to (do shell script "system_profiler SPHardwareDataType | awk '/Model Identifier/ {print $3}'")
set serialNumber to (do shell script "system_profiler SPHardwareDataType | awk '/Serial/ {print $4}'")
set currentDate to "" & (month of (current date)) & " " & (day of (current date)) & ", " & (year of (current date)) & ""
on returnNumbersInString(inputString)
    set s to quoted form of inputString
    do shell script "sed s/[a-zA-Z\\']//g <<< " & s
    set dx to the result
    set numlist to {}
    repeat with i from 1 to count of words in dx
        set this_item to word i of dx
        try
            set this_item to this_item as number
            set the end of numlist to this_item
        end try
    end repeat
    return numlist
end returnNumbersInString
set iconAC to ""
set iconBatt to ""
set iconCharge to ""
set iconTime to ""
set iconHealth to ""
set iconCycles to ""
set iconWarning to "⚠️"
repeat 1 times
    try
        do shell script "pmset -g everything | grep Cycles"
    on error
        set pwrSource to ""
        set pwr to ""
        set charger to " --- "
        set percentage to " --- "
        set _t to "Time Remaining: --- "
        set t to ""
        set battHealth to " --- "
        set cycles to " --- "
        set batteryError to "False"
        exit repeat
    end try
    set x to the result
    set charging to word 2 of x
    if charging contains "Not" then
        set charger to " (not charging)   " & iconWarning
    else
        set charger to " (charging)"
    end if
    if word 1 of x is "AC" then
        set _t to "Time to Full Charge: "
        set pwr to "AC"
        set pwrSource to iconAC
    else
        set _t to "Time Remaining: "
        set pwr to "Internal Battery"
        set pwrSource to iconBatt
        set charger to ""
    end if
    set nums to returnNumbersInString(x)
    set percentage to item 1 of nums
    if percentage is less than or equal to 20 then
        set percentage to item 1 of nums & "% (low battery)"
    else if percentage is less than or equal to 5 then
        set percentage to item 1 of nums & "% (critical battery)"
    else
        set percentage to item 1 of nums & "%"
    end if
    if item 5 of nums = 0 then
        set hrmins to " minutes"
    else if item 5 of nums = 1 then
        set hrmins to " hour"
    else
        set hrmins to " hours"
    end if
    if item 5 of nums is greater than 4 then
        if pwr is "AC" then
            set t to "Calculating..."
        end if
    else
        if item 6 of nums is less than 10 then
            set theMins to item 6 of nums as string
            set theMins to "0" & theMins as string
        else
            set theMins to item 6 of nums as integer
        end if
        set t to item 5 of nums & ":" & theMins & hrmins
    end if
    set FCC to item 3 of nums as integer
    set designCap to item 4 of nums as integer
    set battHealth to (FCC / (designCap / 100))
    set battHealth to round (battHealth)
    set battHealth to battHealth & "%"
    set cycles to item -3 of nums
    set batteryError to "True"
end repeat
display alert "System Information" message "Device Name: " & (computerName) & "
Current Version: " & (osVersion) & "
Current User: " & (currentUser) & "
Current User ID: " & (userId) & "
Public IP Address: " & (ipAddress) & "
Local Area: " & (localArea) & "
Internet Address: " & (ethernetAddress) & "
Internet Status: " & (conStatus) & "
Cores: " & (coreCount) & "
CPU Type: " & (cpuType) & "
CPU Speed: " & (cpuSpeed) & " GHz
Memory: " & (physMemGig) & " GB
Disk Label: " & (diskName) & "
Free Space: " & (freeBytesGigs) & " GB
Model: " & (macModel) & "
Serial: " & (serialNumber) & "
Current Date: " & (currentDate) & "
" & pwrSource & "Power Source: " & pwr & charger & return & iconCharge & "Current Charge: " & percentage & return & iconTime & _t & t & return & iconHealth & "Battery Capacity: " & battHealth & return & iconCycles & "Remaining Cycles: " & cycles & return & "Battery Existence: " & batteryError buttons {"Quit"} default button 1
end repeat

Я продолжал получать синтаксическую ошибку, которая гласила: «Ожидается конец», но найдено «on».

1 Ответ

0 голосов
/ 21 июня 2019

Оболочка AppleScript должна быть объявлена ​​на верхнем уровне кода.

Move

on returnNumbersInString(inputString)
    set s to quoted form of inputString
    do shell script "sed s/[a-zA-Z\\']//g <<< " & s
    set dx to the result
    set numlist to {}
    repeat with i from 1 to count of words in dx
        set this_item to word i of dx
        try
            set this_item to this_item as number
            set the end of numlist to this_item
        end try
    end repeat
    return numlist
end returnNumbersInString

в конце скрипта (после end repeat)

Чтобы повторить код контролируемым образом нажатием кнопки «заменить»

buttons {"Quit"} default button 1 

в строке display alert с

buttons {"Repeat", "Quit"} cancel button "Quit" default button 2

Нажатие кнопки отмены отменяет скрипт

...