如果使用颜色提示,请查看如何修复Python readline中的列计算

我使用标准提示来定制交互式Python会话:

  $ cat ~/.bashrc
export PYTHONSTARTUP=~/.pystartup

  $ cat ~/.pystartup
import os
import sys
import atexit
import readline
import rlcompleter

historyPath = 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='33[32m'
    red='33[31m'
    reset='33[0m'
    sys.ps1 = red + '>>> ' + reset
    sys.ps2 = green + '... ' + reset
del term_with_colors

atexit.register(save_history)
del os, sys, atexit, readline, rlcompleter, save_history, historyPath

现在我得到上下文敏感的完成和颜色提示。

问题来自颜色提示 - 当我在交互式Python会话Readline中调用历史搜索 - 向后搜索 (通过按UP键)时,需要计算终端转义序列,因此计算错误地计算了光标位置并错误地显示了文本。

在Bash man页面中,这个问题被特殊标记提及并修复:

    [     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提示?


我打开信息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  '01'
#define RL_PROMPT_END_IGNORE    '02'

所以我对我的〜/ .pystartup进行了适当的修改:

    green='0133[32m02'
    red='0133[31m02'
    reset='0133[0m02'

现在一切正常!


为了获得更好的python shell体验,我建议你使用ipython或者bpython。

链接地址: http://www.djcxy.com/p/83155.html

上一篇: Look how to fix column calculation in Python readline if use color prompt

下一篇: How do I properly write to FIFOs in Python?