Created
December 14, 2013 19:14
-
-
Save babab/7963551 to your computer and use it in GitHub Desktop.
ANSI colored output of strings
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
# Copyright (c) 2013 Benjamin Althues <benjamin@babab.nl> | |
# | |
# Permission to use, copy, modify, and distribute this software for any | |
# purpose with or without fee is hereby granted, provided that the above | |
# copyright notice and this permission notice appear in all copies. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
import subprocess | |
class AnsiColors(object): | |
_colors = ('red', 'green', 'yellow', 'blue', 'magenta', 'cyan') | |
def __init__(self): | |
def tput(command): | |
try: | |
return subprocess.check_output(('tput ' + command).split()) | |
except subprocess.CalledProcessError: | |
return '' | |
mapping = [('bold', 'bold'), ('clear', 'sgr0')] | |
for i in range(0, 6): | |
mapping.append((self._colors[i], 'setaf ' + str(i + 1))) | |
mapping.append((self._colors[i].upper(), 'setab ' + str(i + 1))) | |
for color, arguments in mapping: | |
setattr(self, color, str(tput(arguments))) | |
def string(self, string, color=None, bold=False, tabbing=0): | |
string = str(string) | |
ret = self.bold if bold else '' | |
if color: | |
try: | |
ret += getattr(self, color) | |
except AttributeError: | |
pass | |
while tabbing > len(string): | |
ret += ' ' | |
tabbing -= 1 | |
ret += string + self.clear | |
return ret | |
def echo(self, string, color=None, bold=False, tabbing=0): | |
print(self.string(string, color, bold, tabbing)) | |
return self | |
def palet(self): | |
self.echo('\n normal text abcdefgABCDEFG1234567890') | |
self.echo(' bold text abcdefgABCDEFG1234567890\n', bold=True) | |
for c in self._colors: | |
print( | |
self.string(string=c, color=c, tabbing=10) | |
+ self.string(string=c.upper(), color=c.upper(), tabbing=10) | |
+ self.string(string=c, color=c, bold=True, tabbing=10) | |
+ self.string(string=c.upper(), color=c.upper(), bold=True, | |
tabbing=10) | |
) | |
return self | |
if __name__ == '__main__': | |
AnsiColors().palet() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment