Created
November 6, 2010 00:53
-
-
Save sumeet/665086 to your computer and use it in GitHub Desktop.
Highlight terms in stdin with different colors.
This file contains hidden or 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
#!/usr/bin/env python | |
""" | |
# highlight | |
Highlight terms in stdin with different colors. | |
Example usage: | |
$ tail -f /some/log_file | highlight batch3 slave master darwin | |
""" | |
import sys | |
colors_map = {'black': '0;30', | |
'blue': '0;34', | |
'green': '0;32', | |
'cyan': '0;36', | |
'red': '0;31', | |
'purple': '0;35', | |
'brown': '0;33', | |
'light_gray': '0;37', | |
'dark_gray': '1;30', | |
'light_blue': '1;34', | |
'light_green': '1;32', | |
'light_cyan': '1;36', | |
'light_red': '1;31', | |
'light_purple': '1;35', | |
'yellow': '1;33', | |
'white': '1;37'} | |
for potentially_bland_color in ('black', 'light_gray', 'dark_gray', 'white'): | |
del colors_map[potentially_bland_color] | |
def color_string(color): | |
return '\033[%sm' % color | |
colors = [color_string(color) for color in colors_map.itervalues()] | |
reset = color_string(0) | |
def colorize(input_string, color): | |
return ''.join((color, input_string, reset)) | |
def highlight(terms, text): | |
for index, term in enumerate(terms): | |
color = colors[index % len(colors)] | |
text = text.replace(term, colorize(term, color)) | |
return text | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print 'Specify some terms to highlight.' | |
sys.exit(1) | |
for line in sys.stdin: | |
sys.stdout.write(highlight(sys.argv[1:], line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment