command-prompt - 如何在 Zsh 提示符中显示电池状态

标签 command-prompt zsh

我认为答案是不言自明的。

我一直在寻找一个已经可以做到这一点的软件,但我还没有找到任何运气。它要么不是在 Zsh 中完成,要么是针对另一个应用程序,例如 tmux。重点是我还没找到它。

所以我的问题是,是否已经有一个预先制作的脚本可以做到这一点?如果有的话请分享一下链接。

如果没有,我应该考虑什么来制作这个脚本?我是 Zsh 脚本的新手,所以请记住这一点。

这个想法是它输出类似 67% 的内容。你明白了。 ;)

最佳答案

other answer不适用于 Mac OS X(没有 apci)。

我已经获取了 Steve Losh's zsh prompt 的一些内容在我的提示下。这并不完全是您想要的 - 箭头 ▸▸▸▸▸▸▸▸▸▸ 显示当前电池状态,并在电池电量不足时改变颜色。此方法使用 Python 脚本,为了完整起见,我将在下面添加该脚本。这是我的提示操作的屏幕截图:

My zsh prompt

提出了另一种适用于 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) $'

看起来像这样:

Reddit-based battery charge.

<小时/>

要使用 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)

关于command-prompt - 如何在 Zsh 提示符中显示电池状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16125498/

相关文章:

bash - 将整个文件读取到变量,保持转义字符完整

ruby-on-rails - 如何让 RVM 在我的 Mac 终端中被识别?

javascript - 找不到 nest 命令

bash - 具有平均背景颜色的壁纸的 Shell 脚本

powershell - 如何更改控制台中的显示powershell(当前路径)?

java - 在 1 个命令行中添加 2 个类路径

batch-file - 使用 Batch 列出任何环境 PATH 中的所有可执行文件

windows - 使用单个窗口命令从文件中提取 N 行

windows - 使用带参数的 "start"命令传递给启动的程序

perforce - 为什么我在 zsh 中的 p4 同步上得到 "protected namespace - access denied"而不是 bash?