Как исправить подсчет столбцов в 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='\033[32m'
    red='\033[31m'
    reset='\033[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

Теперь я получаю контекстно-зависимое завершение и цветную подсказку.

Проблема связана с цветовой подсказкой - когда я вызываю history-search-backward (нажатием UP) в интерактивной сессии Python, Readline учитывает управляющие последовательности терминала, поэтому позиция курсора рассчитывается неверно и текст отображается неверно.

В Bash man page эта проблема упоминается и исправляется специальными маркерами:

    \[     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 prompt?

19
задан wjandrea 26 May 2019 в 05:09
поделиться