Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from __future__ import unicode_literals
  4.  
  5. import re
  6. import sys
  7.  
  8.  
  9. def c(i):
  10. """
  11. Simple shell color output function. (Checks if terminal supports color
  12. before vomitting ANSI codes).
  13.  
  14. Usage:
  15.  
  16. >>> print c('Some <red>Red</end> and <blue>blue</end> text')
  17. >>> print c('<green bg>Some green background</end>')
  18. >>> print c('Some <cyan bold bg>{}</end>').format('interpolation')
  19.  
  20. Note: the keyword in the closing tag isn't really relevant, but I like to
  21. use "</end>" everywhere for shortness and consistency.
  22.  
  23. """
  24. NORMAL, BOLD = (0, 1)
  25. ESC, RESET = ('\033[{};{}m', '\033[1;m')
  26. COLORS = {
  27. 'gray': 30, 'grey': 30, 'red': 31, 'green': 32, 'yellow': 33,
  28. 'blue': 34, 'magenta': 35, 'purple': 35, 'cyan': 36, 'white': 37,
  29. }
  30.  
  31. def ansi(m):
  32. groups = m.groups()
  33. if not COLORS.get(groups[0].split(' ')[0]):
  34. print('Unknown color "{}"'.format(groups[0].split(' ')[0]))
  35.  
  36. if ' ' in groups[0]:
  37. color = COLORS.get(groups[0].split(' ')[0])
  38. weight = 'bold' in groups[0].split(' ') and BOLD or NORMAL
  39. if 'bg' in groups[0].split(' '):
  40. color += 10
  41. else:
  42. color, weight = COLORS.get(groups[0]), NORMAL
  43. return ''.join([ESC.format(weight, color), groups[1], RESET])
  44.  
  45. def text(m):
  46. return m.groups()[1]
  47.  
  48. return re.sub('<([A-Za-z0-9 ]+|\s+)>(.+?)</(\w+)>',
  49. sys.stdout.isatty() and ansi or text, i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement