Skip to content

Instantly share code, notes, and snippets.

@nathants

nathants/color.py

Last active Jun 15, 2020
Embed
What would you like to do?
colorize input text
#!/usr/bin/env python3
"""
colorize input text
usage: echo a b c | color a:green c:red
"""
import functools
import sys
import os
# make colors
_colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
_pairs = zip(_colors, range(31, 38))
def _make_color(code, text):
return "\033[{}m{}\033[0m".format(code, text)
for _color, _num in _pairs:
globals()[_color] = functools.partial(_make_color, _num)
ljust = int(os.environ.get('ljust', '0'))
colors = {token: globals()[color](token)
for arg in sys.argv[1:]
for token, color in [arg.split(':')]}
for line in sys.stdin:
if any(token in line for token in colors):
for token in line.rstrip().split():
if token in colors:
token = colors[token]
if ljust:
token = token.ljust(ljust + 9)
sys.stdout.write(token)
sys.stdout.write(' ')
sys.stdout.write('\n')
else:
sys.stdout.write(line)
sys.stdout.flush()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.