Skip to content

Instantly share code, notes, and snippets.

@svetlyak40wt
Created December 4, 2010 23:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svetlyak40wt/728611 to your computer and use it in GitHub Desktop.
Save svetlyak40wt/728611 to your computer and use it in GitHub Desktop.
Console output colorizator.
#!/usr/bin/env python
"""
Console output colorizator
Author: Alexander Artemenko <svetlyak.40wt@gmail.com>
Usage: tail -f some.log | colorize.py 'one.*pattern' 'another'
DON'T DOWNLOAD THIS SCRIPT. JUST INSTALL IT USING easy_install colorize
OR FORK IT https://github.com/svetlyak40wt/colorize
"""
import sys
import re
from termcolor import colored, COLORS
from itertools import starmap
COLORS = [c for c in COLORS.keys() if c != 'grey']
class Colorer:
def __init__(self, regex, color):
self.regex = re.compile(regex)
self.color = color
def __call__(self, line):
return self.regex.sub(lambda x: colored(x.group(0), self.color), line)
COLORERS = list(starmap(Colorer, zip(sys.argv[1:], COLORS)))
def process(line):
for colorer in COLORERS:
line = colorer(line)
return line
if __name__ == '__main__':
if len(sys.argv[1:]) > len(COLORS):
sys.stderr.write('Num arguments should not be more than %s.\n' % len(COLORS))
sys.exit(1)
for line in sys.stdin.xreadlines():
sys.stdout.write(process(line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment