2

I am trying to use colored prompt for cmd module in python.

prompt.py

from cmd import Cmd

from utils.data_types import Str

class Prompt(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self.prompt = "prompt ({}) > ".format(Str("home").red())

    def emptyline(self):
        pass

data_types.py

class Str(str):
    def red(self):
        return "\033[31m{}\033[0m".format(self)

    def green(self):
        return "\033[32m{}\033[0m".format(self)

    def yellow(self):
        return "\033[33m{}\033[0m".format(self)

    def blue(self):
        return "\033[34m{}\033[0m".format(self)

with this code, if I keep typing in the prompt, if there is no space at the end it should go to a newline but it's overwriting the sameline.

issue

I looked into the cmd.py file, it using input method and readline. I thought it might the problem with input method, I tried the following it works fine, only when I using cmd module the prompt breaks.

inp = input("prompt ({}) > ".format(Str("home").red()))

Edited:

I think the problem with readline, whenever I import readline the prompt breaks, if I don't import readline the prompt works fine. Is this a bug?

apparently not a bug: https://bugs.python.org/issue12972

Jeeva
  • 3,975
  • 3
  • 23
  • 47
  • 1
    Possible duplicate of [Look how to fix column calculation in Python readline if use color prompt](https://stackoverflow.com/questions/9468435/look-how-to-fix-column-calculation-in-python-readline-if-use-color-prompt) – wjandrea May 25 '19 at 23:36

1 Answers1

2

turns out that it's not an issue with python. Rather, this is a quirk with how readline works...

Look how to fix column calculation in Python readline if use color prompt

Color prompts need to be wrapped by RL_PROMPT_START_IGNORE and RL_PROMPT_END_IGNORE.

Jeeva
  • 3,975
  • 3
  • 23
  • 47