zsh和python。尝试在zsh提示符中使用python脚本,但是

2024-06-28 16:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想用python脚本在zsh提示符上显示我的笔记本电脑的电池状态。 我在跟踪this。你知道吗

我在~/bin/中编写了batcharge.py脚本,在commad行中编写了chmod 755 batcharge.py。你知道吗

这是批处理.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

我重新启动了我的外壳,但是它一直在显示 “%$”(电池电量)

我哪里做错了?你知道吗


Tags: inpy脚本ifbinmathoutmax
1条回答
网友
1楼 · 发布于 2024-06-28 16:32:05

您需要启用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

更简单地说,由于每次使用precmd钩子显示RPROMPT时都要设置它的值,因此首先不需要嵌入命令替换。直接设置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

相关问题 更多 >