【问题标题】:Why can't I use colored prompt with python CMD module?为什么我不能在 python CMD 模块中使用彩色提示?
【发布时间】:2019-10-12 01:05:17
【问题描述】:

我正在尝试在 python 中为cmd 模块使用彩色提示。

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)

使用此代码,如果我继续在提示中输入,如果末尾没有空格,它应该转到换行符,但它会覆盖同一行。

我查看了cmd.py 文件,它使用input 方法和readline。我认为这可能是input方法的问题,我尝试了以下它工作正常,只有当我使用cmd模块时提示中断。

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

已编辑:

我认为readline 的问题是,每当我导入readline 时,提示符都会中断,如果我不导入readline,则提示符工作正常。这是一个错误吗?

显然不是错误:https://bugs.python.org/issue12972

【问题讨论】:

标签: python


【解决方案1】:

原来这不是 python 的问题。相反,这是 readline 工作方式的一个怪癖......

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

颜色提示需要用 RL_PROMPT_START_IGNORE 和 RL_PROMPT_END_IGNORE 包裹起来。

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2023-03-29
    • 2012-02-10
    相关资源
    最近更新 更多