gpt4 book ai didi

python - 如何防止 Python 脚本中的 ANSI 转义序列干扰我的 zsh RPROMPT 和光标位置?

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:34 25 4
gpt4 key购买 nike

我一直在开发一个 Python 脚本,该脚本为 zsh 生成有关当前工作目录中 git 存储库状态的 RPROMPT。它在我的 .zshrc 文件中调用:

RPROMPT='$(python3 ~/.git_zsh_rprompt.py)'

为了将其与终端中的其他文本区分开来,我使用 ANSI 转义码将其设为粗体,并根据存储库是干净还是脏来为其着色。无论出于何种原因,添加这些转义码都会导致我的 RPROMPT 向左移动,并且还将我的光标移动到左侧 PROMPT 的顶部。这是一个表示,其中的 block 代表我的光标:

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="")

最佳答案

您想要在提示中的 ANSI 转义周围使用 %{ %} ZSH 转义序列,如文档 here 所示。

%{...%}

Include a string as a literal escape sequence. The stringwithin the braces should not change the cursor position. Brace pairscan nest.

A positive numeric argument between the % and the { is treated asdescribed for %G below.

关于python - 如何防止 Python 脚本中的 ANSI 转义序列干扰我的 zsh RPROMPT 和光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30470306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com