other answer 不适用于 Mac OS X(没有 apci)。
我在提示符中使用了一些Steve Losh's zsh prompt。这并不完全符合您的要求 - 箭头 ▸▸▸▸▸▸▸▸▸▸ 显示当前电池状态,并在电池电量不足时更改颜色。此方法使用 Python 脚本,为了完整起见,我将在下面添加。这是我的提示的屏幕截图:
OS X 的另一种方法是on Reddit,使用另一个短脚本:
ioreg -n AppleSmartBattery -r | awk '$1~/Capacity/{c[$1]=$3} END{OFMT="%.2f%%"; max=c["\"MaxCapacity\""]; print (max>0? 100*c["\"CurrentCapacity\""]/max: "?")}'
ioreg -n AppleSmartBattery -r | awk '$1~/ExternalConnected/{gsub("Yes", "+");gsub("No", "%"); print substr($0, length, 1)}'
假设这个脚本保存在~/bin/battery.sh:
function battery {
~/bin/battery.sh
}
setopt promptsubst
PROMPT='$(battery) $'
看起来像这样:
要使用 Steve Losh 的脚本,请将脚本保存在某处,然后在上面的 battery() 函数中使用。
适用于 OS X 的电池充电 Python 脚本
#!/usr/bin/env python
# coding=UTF-8
import math, subprocess
p = subprocess.Popen(["ioreg", "-rc", "AppleSmartBattery"], stdout=subprocess.PIPE)
output = p.communicate()[0]
o_max = [l for l in output.splitlines() if 'MaxCapacity' in l][0]
o_cur = [l for l in output.splitlines() if 'CurrentCapacity' in l][0]
b_max = float(o_max.rpartition('=')[-1].strip())
b_cur = float(o_cur.rpartition('=')[-1].strip())
charge = b_cur / b_max
charge_threshold = int(math.ceil(10 * charge))
# Output
total_slots, slots = 10, []
filled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u'▸'
empty = (total_slots - len(filled)) * u'▹'
out = (filled + empty).encode('utf-8')
import sys
color_green = '%{[32m%}'
color_yellow = '%{[1;33m%}'
color_red = '%{[31m%}'
color_reset = '%{[00m%}'
color_out = (
color_green if len(filled) > 6
else color_yellow if len(filled) > 4
else color_red
)
out = color_out + out + color_reset
sys.stdout.write(out)