| thighlighttext.py - sphere - GPU-based 3D discrete element method algorithm wit… | |
| git clone git://src.adamsgaard.dk/sphere | |
| Log | |
| Files | |
| Refs | |
| LICENSE | |
| --- | |
| thighlighttext.py (1292B) | |
| --- | |
| 1 #!/usr/bin/env python | |
| 2 # ANSI color coded text if the terminal supports it. No external require… | |
| 3 # Inspired by | |
| 4 # http://korbinin.blogspot.dk/2012/10/color-text-output-from-python.html | |
| 5 | |
| 6 import sys | |
| 7 | |
| 8 def highlight(string, fg, bold=False): | |
| 9 ''' | |
| 10 Return `string` with ANSI color codes. | |
| 11 | |
| 12 :param string: String to colorize. | |
| 13 :type string: str | |
| 14 :param fg: Foreground text color. Possible values: 'g', 'green', 'r… | |
| 15 'y', 'yellow', 'b', 'blue', 'm' or 'magenta' | |
| 16 :type fg: str | |
| 17 :param bold: Bold text | |
| 18 :type bold: bool | |
| 19 | |
| 20 :returns: ANSI formatted string, can be `print()`'ed directly. | |
| 21 :return type: str | |
| 22 ''' | |
| 23 | |
| 24 attr = [] | |
| 25 if sys.stdout.isatty(): | |
| 26 | |
| 27 if fg == 'g' or fg == 'green': | |
| 28 attr.append('32') | |
| 29 | |
| 30 elif fg == 'r' or fg == 'red': | |
| 31 attr.append('31') | |
| 32 | |
| 33 elif fg == 'y' or fg == 'yellow': | |
| 34 attr.append('33') | |
| 35 | |
| 36 elif fg == 'b' or fg == 'blue': | |
| 37 attr.append('34') | |
| 38 | |
| 39 elif fg == 'm' or fg == 'magenta': | |
| 40 attr.append('35') | |
| 41 | |
| 42 else: | |
| 43 raise Exception('Error: Foreground color `fg` value not unde… | |
| 44 | |
| 45 if bold: | |
| 46 attr.append('1') | |
| 47 | |
| 48 return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) | |
| 49 | |
| 50 else: | |
| 51 return string |