zsh和python。试图在zsh提示符下使用python脚本,但是不能

时间:2019-12-18 06:43:03

标签: python zsh prompt

嗨,我正在尝试使用python脚本在zsh提示符下显示笔记本电脑的电池状态。 我正在关注this

我在自己的batcharge.py中制作了~/bin/脚本,在一行中做了chmod 755 batcharge.py

这是batcharge.py脚本

#!/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)

这是我的.zshrc脚本。

BAT_CHARGE=~/bin/batcharge.py
function battery_charge {
    echo `$BAT_CHARGE` 2>/dev/null
}
set_prompt(){
NEWLINE=$'\n'
PROMPT="%F{202}%n%f at %F{136}%m%f in %F{green}%1~%f${NEWLINE}%# "
RPROMPT='$(battery_charge)'
}
autoload add-zsh-hook
add-zsh-hook precmd set_prompt

,我重新启动了外壳程序,但是它一直显示 '%$(电池充电)

我在哪里做错了?

1 个答案:

答案 0 :(得分:2)

您需要启用PROMPT_SUBST选项,以便在提示中评估命令替换。

(此外,无需定义BAT_CHARGEbattery_charge;只需直接从提示符处调用Python脚本即可。)

setopt PROMPT_SUBST
set_prompt(){
  NEWLINE=$'\n'
  PROMPT="%F{202}%n%f at %F{136}%m%f in %F{green}%1~%f${NEWLINE}%# "
  RPROMPT='$(~/bin/batcharge.py)'
}
autoload add-zsh-hook
add-zsh-hook precmd set_prompt

更简单地说,由于每次使用RPROMPT钩子显示时都要设置precmd的值,因此首先不需要嵌入式命令替换。只需直接设置RPROMPT

set_prompt(){
  NEWLINE=$'\n'
  PROMPT="%F{202}%n%f at %F{136}%m%f in %F{green}%1~%f${NEWLINE}%# "
  RPROMPT=$(~/bin/batcharge.py)
}
autoload add-zsh-hook
add-zsh-hook precmd set_prompt