【发布时间】:2015-08-08 19:42:48
【问题描述】:
我一直在编写一个 Python 脚本,它为 zsh 生成一个关于当前工作目录中 git repo 状态的 RPROMPT。它在我的 .zshrc 文件中调用:
RPROMPT='$(python3 ~/.git_zsh_rprompt.py)'
为了将它与终端中的其他文本区分开来,我使用了 ANSI 转义码使其变为粗体,并根据 repo 是干净还是脏了颜色。无论出于何种原因,添加这些转义码导致我的 RPROMPT 向左移动,并且它也将我的光标移到了我的左侧 PROMPT 上方。这是一个表示,块代表我的光标:
jared@Jareds-Mac⌷ook-Pro:foobar% master( +2 ~4 )
除了一些未受过教育的猜测之外,我不完全确定为什么会发生这种情况。我希望这里有人这样做并且知道解决方案或解决方法,可以将所有内容恢复到应有的位置。作为参考,这是有问题的脚本:
from collections import Counter
from os import devnull
from subprocess import call, check_output, STDOUT
def git_is_repo():
command = ["git", "branch"]
return not call(command, stderr = STDOUT, stdout = open(devnull, "w"))
def git_current_branch():
command = ["git", "branch", "--list"]
lines = check_output(command).decode("utf-8").strip().splitlines()
return next((line.split()[1] for line in lines if line.startswith("* ")),
"unknown branch")
def git_status_counter():
command = ["git", "status", "--porcelain"]
lines = check_output(command).decode("utf-8").strip().splitlines()
return Counter(line.split()[0] for line in lines)
if __name__ == "__main__":
if git_is_repo():
counter = git_status_counter()
# Print bold green if the repo is clean or bold red if it is dirty.
if counter.elements() == []:
print("\033[1;32m", end="")
else:
print("\033[1;31m", end="")
print(git_current_branch(), end="")
# Only print status counters if the repo is dirty.
if counter.elements() != []:
print("(", end="")
if counter["??"] != 0:
print(" +{}".format(counter["??"]), end="")
if counter["M"] != 0:
print(" ~{}".format(counter["M"]), end="")
if counter["D"] != 0:
print(" -{}".format(counter["D"]), end="")
print(" )", end="")
# Reset text attributes.
print("\033[0m", end="")
【问题讨论】:
标签: python zsh ansi-escape