【问题标题】:ZSH & Python: python as shell environment variable?ZSH & Python:python 作为 shell 环境变量?
【发布时间】:2011-02-08 10:03:19
【问题描述】:

我一直在研究如何设置 ZSH。我已经擦除了我的机器 (Mac OS X),安装了 XCode (Python),运行了 chsh -s zsh,并安装了 oh-my-zsh。

大众似乎对 Steve Losh 的“散文”主题以及他在制作过程中编写的教程赞不绝口。我已经能够在其中包含与我相关的所有内容,除了电池信息部分。代码如下:

“我已将此脚本放在我的~/bin/ 目录中的一个名为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

function battery_charge {
    echo `$BAT_CHARGE` 2>/dev/null
}

稍后在.zshrc

RPROMPT='$(battery_charge)'

我已经这样做了,但是终端/iTerm 中没有出现电池图标。我理解的差距在于$BAT_CHARGE 调用和~/bin/ 放置。 Steve 指定“你当然可以命名它并将它放置在任何你喜欢的地方/任何地方......”如果是这样,如果你将 python 文件放在某个随机位置,你的 shell 怎么知道分配 $BAT_CHARGE 的值?

感谢您的建议,

JW

【问题讨论】:

    标签: python zsh zshrc


    【解决方案1】:

    因为在文件的前面,您应该将脚本的位置分配给环境变量(或完全省略环境变量并直接使用脚本位置)。

    【讨论】:

    • 您能详细说明一下吗?这是用#!/usr/bin/env Python 行处理的吗?我将如何直接使用脚本位置(我假设这是参考 .zshrc 文件)?
    • 不,你必须自己做。 BAT_CHARGE=~/bin/batcharge.pyecho ~/bin/batcharge.py` 2>/dev/null`.
    • 谢谢!我将BAT_CHARGE=~/.zshfuncs/batcharge.py 添加到.zsh 主题中,然后添加chmod 755 batcharge.py,一切都非常好。感谢您的及时回复!
    • 我也尝试过,但我无法让它解析字符串的颜色格式部分。它只是写“[32m-⚡⚡⚡⚡⚡⚡⚡⚡⚡⚡[00m”,而不是写成绿色的“-⚡⚡⚡⚡⚡⚡⚡⚡⚡”。使用稍微修改的函数,但与 python 脚本的输出格式相同,并在我的 zsh 主题文件中以完全相同的方式调用它。
    • @Thriveth:您确定您的终端使用这些序列进行着色吗?
    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2018-12-02
    相关资源
    最近更新 更多