codekingpro/portable-devtools
114k
1# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.2'''3This module generates ANSI character codes to printing colors to terminals.4See: http://en.wikipedia.org/wiki/ANSI_escape_code5'''6 7CSI = '\033['8OSC = '\033]'9BEL = '\a'10 11 12def code_to_chars(code):13 return CSI + str(code) + 'm'14 15def set_title(title):16 return OSC + '2;' + title + BEL17 18def clear_screen(mode=2):19 return CSI + str(mode) + 'J'20 21def clear_line(mode=2):22 return CSI + str(mode) + 'K'23 24 25class AnsiCodes(object):26 def __init__(self):27 # the subclasses declare class attributes which are numbers.28 # Upon instantiation we define instance attributes, which are the same29 # as the class attributes but wrapped with the ANSI escape sequence30 for name in dir(self):31 if not name.startswith('_'):32 value = getattr(self, name)33 setattr(self, name, code_to_chars(value))34 35 36class AnsiCursor(object):37 def UP(self, n=1):38 return CSI + str(n) + 'A'39 def DOWN(self, n=1):40 return CSI + str(n) + 'B'41 def FORWARD(self, n=1):42 return CSI + str(n) + 'C'43 def BACK(self, n=1):44 return CSI + str(n) + 'D'45 def POS(self, x=1, y=1):46 return CSI + str(y) + ';' + str(x) + 'H'47 48 49class AnsiFore(AnsiCodes):50 BLACK = 3051 RED = 3152 GREEN = 3253 YELLOW = 3354 BLUE = 3455 MAGENTA = 3556 CYAN = 3657 WHITE = 3758 RESET = 3959 60 # These are fairly well supported, but not part of the standard.61 LIGHTBLACK_EX = 9062 LIGHTRED_EX = 9163 LIGHTGREEN_EX = 9264 LIGHTYELLOW_EX = 9365 LIGHTBLUE_EX = 9466 LIGHTMAGENTA_EX = 9567 LIGHTCYAN_EX = 9668 LIGHTWHITE_EX = 9769 70 71class AnsiBack(AnsiCodes):72 BLACK = 4073 RED = 4174 GREEN = 4275 YELLOW = 4376 BLUE = 4477 MAGENTA = 4578 CYAN = 4679 WHITE = 4780 RESET = 4981 82 # These are fairly well supported, but not part of the standard.83 LIGHTBLACK_EX = 10084 LIGHTRED_EX = 10185 LIGHTGREEN_EX = 10286 LIGHTYELLOW_EX = 10387 LIGHTBLUE_EX = 10488 LIGHTMAGENTA_EX = 10589 LIGHTCYAN_EX = 10690 LIGHTWHITE_EX = 10791 92 93class AnsiStyle(AnsiCodes):94 BRIGHT = 195 DIM = 296 NORMAL = 2297 RESET_ALL = 098 99Fore = AnsiFore()100Back = AnsiBack()101Style = AnsiStyle()102Cursor = AnsiCursor()103 