#!/usr/bin/env python
"""
Print an highlighted version of string (POSIX only).
Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
"""
import sys
def hilite(string, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
attr = []
if ok is None: # no color
pass
elif ok: # green
attr.append('32')
else: # red
attr.append('31')
if bold:
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
if not sys.stdout.isatty(): # not bound to a terminal
hilite = lambda s, *args, **kwargs: s
if __name__ == '__main__':
print hilite('hello')
print hilite('hello', ok=False)
print hilite('hello', ok=True, bold=True)
print hilite('hello', ok=False, bold=True)
print hilite('hello', ok=None, bold=False)
print hilite('hello', ok=None, bold=True)
Diff to Previous Revision
--- revision 1 2011-12-03 11:47:48
+++ revision 2 2012-01-30 20:14:14
@@ -1,7 +1,7 @@
#!/usr/bin/env python
"""
-Print an highlighted version of string.
+Print an highlighted version of string (POSIX only).
Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
@@ -22,8 +22,8 @@
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
-if not sys.stdout.isatty():
- hilite = lambda string, **kw: string
+if not sys.stdout.isatty(): # not bound to a terminal
+ hilite = lambda s, *args, **kwargs: s
if __name__ == '__main__':
print hilite('hello')