用applescript检测电池百分比

时间:2016-07-18 22:51:12

标签: applescript osx-yosemite

我如何检测计算机的电池电量百分比,并使用applescript将其设置为变量?类似问题的所有答案都说要安装其他软件,但我想用纯苹果脚本来做。这可能吗?我也试过在applescript库中搜索没有成功。

3 个答案:

答案 0 :(得分:7)

on run
    set theBattString to (do shell script "pmset -g batt")
    -- the above will return something like...
    -- Now drawing from 'Battery Power' -InternalBattery-0  82%; discharging; 4:06 remaining
end run

现在,您可以解析theBattString以获取您喜欢的信息。

另一种选择......

on run
    do shell script "ioreg -l | grep -i capacity | tr '\\n' ' | ' | awk '{printf(\"%.2f%%\\n\", $10/$5 * 100)}'"
    -- will output...
    -- 79.63%
end run

答案 1 :(得分:0)

applescript无符号变量可以像已签名的FileMaker变量一样使用... **可以删除,我尝试过将其加粗

设置 batteryPercent 以执行shell脚本“ pmset -g batt”

告诉应用程序“ FileMaker Pro.app” 告诉表“功率测试结果” 告诉记录1 将单元格“通过AppleScript Global的测试百分比”设置为 batteryPercent 结束告诉 结束告诉 结束告诉

答案 2 :(得分:-1)

感谢ThrowBackDewd的回答。

我做了一些奇怪的事情,但是对我有用。

这是AppleScript

[编辑]

由于用户@ user3439894,这里的代码效率更高。

    set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")

if batteryPercent < 40 then

    beep

    repeat 3 times

        say "Attention " & batteryPercent & "%" & " before shut down."

        display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"

    end repeat

end if

空闲应用

    on idle

    set batteryPercent to word 6 of paragraph 2 of (do shell script "pmset -g batt")

    if batteryPercent < 40 then



        repeat 3 times

            beep

            say "Attention " & batteryPercent & "%" & " of charge before shut down."

            display notification "Attention " & batteryPercent & "%" & " of charge before shut down." sound name "Glass"

        end repeat

    end if

    return 60

end idle

[第一篇文章]

  set theBattString to (do shell script "pmset -g batt")
-- the above will return something like...
-- Now drawing from 'Battery Power' -InternalBattery-0  82%; discharging; 4:06 remaining

set batteryLevel to splitText(theBattString, space)

--set totalItembatLvl to length of batteryLevel


set remainingTime to item 9 of batteryLevel

if remainingTime < "2:40" then
    display alert "low battery " & remainingTime & " before shut down."
    --batteryLevel & " " & remainingTime
end if


on splitText(theText, theDelimiter)
    set AppleScript's text item delimiters to theDelimiter
    set theTextItems to every text item of theText
    set AppleScript's text item delimiters to ""
    return theTextItems
end splitText
on getPositionOfItemInList(theItem, theList)
    repeat with a from 1 to count of theList
        if item a of theList is theItem then return a
    end repeat
    return 0
end getPositionOfItemInList

您可以将其添加到空闲语句中,并每分钟检查一次电池电量。

任何建议或更正将不胜感激。

致谢。