Created
May 28, 2020 21:17
-
-
Save tweekmonster/448bf742e58bdb30e53a50f65bffded5 to your computer and use it in GitHub Desktop.
Simple colored ANSI sequence text printing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
BLACK = 0 | |
RED = 1 | |
GREEN = 2 | |
YELLOW = 3 | |
BLUE = 4 | |
MAGENTA = 5 | |
CYAN = 6 | |
WHITE = 7 | |
RESET = 9 | |
class ColorStr(str): | |
fg = None | |
bg = None | |
def __str__(self): | |
s = super().__str__() | |
if not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty(): | |
return s | |
if self.fg is not None: | |
s = '\033[%dm%s\033[%dm' % (30 + self.fg, s, 30 + RESET) | |
if self.bg is not None: | |
s = '\033[%dm%s\033[%dm' % (40 + self.bg, s, 40 + RESET) | |
return s | |
def __add__(self, other): | |
return str(self) + str(other) | |
def __radd__(self, other): | |
return str(other) + str(self) | |
def __mul__(self, n): | |
return str(self).__mul__(n) | |
__rmul__ = __mul__ | |
class RedText(ColorStr): | |
fg = RED | |
class GreenText(ColorStr): | |
fg = GREEN | |
class BlueText(ColorStr): | |
fg = BLUE | |
class ErrorText(ColorStr): | |
fg = BLACK | |
bg = RED | |
if __name__ == "__main__": | |
r = RedText | |
g = GreenText | |
b = BlueText | |
err = ErrorText | |
text = '{}, {}, {}'.format(r('Red'), g('Green'), b('Blue')) | |
print(text) | |
print(err(' Test ') + ', ' + r('One') + ', ' + g('Two') + ', ' + b('Three')) | |
print('x' + g(' Repeat ') * 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment