一些字符贴在我的Python cmd中的彩色提示符上

Ram*_*che 9 python colors readline command-line-interface python-2.x

我正在使用Python 2的cmd模块为程序创建命令行.只要我不在我的提示中添加颜色,一切都很好用.

工作代码:

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()
Run Code Online (Sandbox Code Playgroud)

当我更改下面的代码时,如果我输入一个长命令或尝试搜索命令历史记录,一些字符会坚持我的提示.

问题代码:

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()
Run Code Online (Sandbox Code Playgroud)

你可以在asciicasts中看到这个问题.cmd2模块也存在问题.

cxw*_*cxw 7

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

    colorcodes =    {'green':{True:'\x01\x1b[32m\x02',False:'\x01\x1b[39m\x02'}}
                                  # ^^^^        ^^^^         ^^^^        ^^^^
Run Code Online (Sandbox Code Playgroud)

在您的asciicast中,当您离开i-search模式并重新打印提示时,您会遇到问题.这是因为Python不知道转义字符实际上不占用屏幕上的空间.放在\x01每个转义序列之前,并\x02在每个转义序列之后,告诉Python假设这些字符不占用空间,因此提示将被正确地重新打印.

这与本答案中的解决方案相同,在不同的上下文中存在相应的问题.在Python readline文档中有一个未解决的问题,但我没有看到它已经完成.

colorcodes在Cygwin上用Python 2.7.12 测试了上面的值,运行时很少.在提示中,username打印绿色和其他一切打印默认(浅灰色).我使用的是标准系统cmd模块,而不是 cmd2(您链接的).