【发布时间】:2014-07-24 18:28:40
【问题描述】:
我正在尝试将我的 zsh RPROMPT 设置为在 this guide 中显示我当前的电池状态。
我编写了以下 python 脚本来查找当前电池状态并打印出格式化的电池状态以供我的 .zshrc 读取。
# Outputs current battery status formatted for use in zsh prompt.
#! /usr/bin/python2.7
# coding=UTF-8
import sys
def main():
file = open('/sys/class/power_supply/BAT0/capacity', 'r')
data = file.read()
file.close()
charge = int(data)
if charge >= 75:
prompt = '%{$fg[green]%} * * * *'
elif charge < 75 and charge >= 50:
prompt = '%{$fg[green]%} * * *'
elif charge < 50 and charge >= 25:
prompt = '%{$fg[yellow]%} * *'
elif charge < 25:
prompt = '%{$fg[red]%} *'
file = open('/sys/class/power_supply/BAT0/status', 'r')
status = file.read()
file.close()
if status == 'Charging\n':
prompt = prompt + '%{$fg[green]%} (+)'
elif status == 'Unknown\n':
prompt = prompt + '%{$fg[yellow]%} (?)'
else:
prompt = prompt + '%{$fg[red]%} (-)'
sys.stdout.write(prompt)
if __name__ == '__main__':
main()
我将此脚本放在我的路径中,以便只需键入“电池”即可运行它。这是我的 .zshrc:
# The following lines were added by compinstall
zstyle ':completion:*' completer _expand _complete _ignored _correct _approximate
zstyle ':completion:*' matcher-list '' ''
zstyle :compinstall filename '/home/jav/.zshrc'
autoload -Uz compinit promptinit
compinit
promptinit
# End of lines added by compinstall
# Lines configured by zsh-newuser-install
HISTFILE=~/.histfile
HISTSIZE=1000
SAVEHIST=1000
setopt autocd
bindkey -v
# End of lines configured by zsh-newuser-install
function prompt {
echo
echo '$ '
}
function battery_status {
echo `battery`
}
autoload -U colors && colors
setopt promptsubst
PROMPT='%{$fg[white]%}[%n @ %M in %~]$(prompt)'
RPROMPT=$(battery_status)%{$reset_color%}
总共显示类似于以下内容。
[username @ hostname in ~] * * * * (-)
$
星号代表当前电池电量,“(-)”代表是否正在充电。问题是“* * * * (-)”应在插入交流适配器或电池电量发生变化时自动更新,但事实并非如此。我必须'source .zshrc'才能更新电池状态。
我知道RPROMPT=$(battery_status)%{$reset_color%} 应该用像RPROMPT='$(battery_status)%{$reset_color%}' 这样的单引号括起来,但是当我这样做而不是提示显示'* * * *(-)' 时,它会显示python 程序的文字输出:" %{$fg[green]%} * * * *%{$fg[red]%} (-)"
只有在我的 .zshrc 中的 shell 函数中使用 python 程序时才会出现此问题。 RPROMPT 中使用的 Shell 脚本可以正确更新。
每次运行时,我都会将 python 电池程序记录到一个文件中。根据日志文件,电池程序仅在获取 .zshrc 时运行,而不是每次向终端打印新提示时运行。
由于它只发生在 python 程序中,这让我认为这是我如何打印输出的问题。但是看到每次在终端中显示提示时都没有运行电池脚本,我觉得这可能是我在 zsh 方面犯的一个错误。
我做错了什么?
【问题讨论】:
标签: shell python-2.7 zsh