I am using Python 2's cmd module to make a command line for a program. Everything works nicely as long as I don't add color to my prompt.
Working code:
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()
When I change my code as below, if I enter a long command or try to search in the command history, some characters stick to my prompt.
Problem code:
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()
You can see this problem in asciicasts. The problem also exists with the cmd2 module.