gpt4 book ai didi

python - 如果使用颜色提示,如何修复 Python readline 中的列计算

转载 作者:IT老高 更新时间:2023-10-28 20:52:27 26 4
gpt4 key购买 nike

我使用标准技巧来定制交互式 Python session :

$ cat ~/.bashrcexport PYTHONSTARTUP=~/.pystartup$ cat ~/.pystartupimport osimport sysimport atexitimport readlineimport rlcompleterhistoryPath = os.path.expanduser("~/.pyhistory")def save_history(historyPath=historyPath):    import readline    readline.write_history_file(historyPath)if os.path.exists(historyPath):    readline.read_history_file(historyPath)term_with_colors = ['xterm', 'xterm-color', 'xterm-256color', 'linux', 'screen', 'screen-256color', 'screen-bce']if os.environ.get('TERM') in term_with_colors:    green='\033[32m'    red='\033[31m'    reset='\033[0m'    sys.ps1 = red + '>>> ' + reset    sys.ps2 = green + '... ' + resetdel term_with_colorsatexit.register(save_history)del os, sys, atexit, readline, rlcompleter, save_history, historyPath

现在我得到了上下文相关的完成和颜色提示。

问题来自颜色提示 - 当我在交互式 Python session 中调用 history-search-backward(通过按 UP)时,Readline 会考虑终端转义序列,所以光标位置计算错误,文字显示错误。

在 Bash 手册页中,这个问题被提及并通过特殊标记修复:

    \[     begin a sequence of non-printing characters,           which could be used to embed a           terminal control sequence into the prompt    \]     end a sequence of non-printing characters

如何解决 Python 提示的这个问题?

最佳答案

我打开info readline发现:

 -- Function: int rl_expand_prompt (char *prompt)     Expand any special character sequences in PROMPT and set up the     local Readline prompt redisplay variables.  This function is     called by `readline()'.  It may also be called to expand the     primary prompt if the `rl_on_new_line_with_prompt()' function or     `rl_already_prompted' variable is used.  It returns the number of     visible characters on the last line of the (possibly multi-line)     prompt.  Applications may indicate that the prompt contains     characters that take up no physical screen space when displayed by     bracketing a sequence of such characters with the special markers     `RL_PROMPT_START_IGNORE' and `RL_PROMPT_END_IGNORE' (declared in     `readline.h'.  This may be used to embed terminal-specific escape     sequences in prompts.

按照文字提示,我在 readline.h 中搜索了 RL_PROMPT_START_IGNORERL_PROMPT_END_IGNORE 定义,然后找到了下一个:

/* Definitions available for use by readline clients. */#define RL_PROMPT_START_IGNORE  '\001'#define RL_PROMPT_END_IGNORE    '\002'

所以我对我的 ~/.pystartup 进行了适当的更改:

    green='\001\033[32m\002'    red='\001\033[31m\002'    reset='\001\033[0m\002'

现在一切正常!!!

关于python - 如果使用颜色提示,如何修复 Python readline 中的列计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9468435/

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