在Python cmd中,一些字符会粘贴到我的彩色提示

在Python cmd中,一些字符会粘贴到我的彩色提示,python,colors,command-line-interface,python-2.x,readline,Python,Colors,Command Line Interface,Python 2.x,Readline,我正在使用为一个程序制作一个命令行。只要我不给提示符添加颜色,一切都很好 工作代码: from cmd import Cmd class App(Cmd): def __init__(self): Cmd.__init__(self) self.prompt = "PG ["+ (str('username'), 'green') +"@"+ str('hostname') +"]: " def do_exit(self, line):

我正在使用为一个程序制作一个命令行。只要我不给提示符添加颜色,一切都很好

工作代码:

from cmd import Cmd

class App(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.prompt = "PG ["+ (str('username'), 'green') +"@"+ str('hostname') +"]: "

    def do_exit(self, line):
        '''
        '''
        return True

App().cmdloop()
当我按如下方式更改代码时,如果我输入一个较长的命令或尝试在命令历史记录中搜索,一些字符会粘在我的提示符上

问题代码:

from cmd import Cmd

class App(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.prompt = "PG ["+ self.colorize(str('username'), 'green') +"@"+ str('hostname') +"]: "

    colorcodes =    {'green':{True:'\x1b[32m',False:'\x1b[39m'}}


    def colorize(self, val, color):
        return self.colorcodes[color][True] + val + self.colorcodes[color][False]

    def do_exit(self, line):
        '''
        '''
        return True

App().cmdloop()

你可以从中看到这个问题。问题也存在于。

只需在颜色代码中添加标记:

    colorcodes =    {'green':{True:'\x01\x1b[32m\x02',False:'\x01\x1b[39m\x02'}}
                                  # ^^^^        ^^^^         ^^^^        ^^^^
在AsciCast中,离开i-search模式并重新打印提示时出现问题。这是因为Python不知道转义字符实际上不会占用屏幕空间。将
\x01
放在每个转义序列之前,将
\x02
放在每个转义序列之后,会告诉Python假定这些字符不占用任何空间,因此将正确地重新打印提示

这是与中相同的解决方案,在不同的上下文中有相应的问题。在Python的readline文档中有提到这一点的例子,但我不认为它已经完成了


我在Cygwin上用Python 2.7.12测试了上述
colorcodes
值,并在mintty中运行。在提示符中,
username
打印为绿色,其他所有内容打印为默认值(浅灰色)。我使用了标准系统
cmd
模块,而不是
cmd2
(您链接的)。

@cxw是的,它是Python2和
cmd
,但是
cmd2
中也存在这个问题!非常感谢你!我在基于
的readline接口上遇到了这个问题,这让我发疯。最后,我找到了一些难看的解决方法,将彩色提示符的某些部分包含在
print()
中,并使用
end='
input()
中。这个答案正是我想要的,但在我需要的时候却找不到。