You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ansi.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
  2. '''
  3. This module generates ANSI character codes to printing colors to terminals.
  4. See: http://en.wikipedia.org/wiki/ANSI_escape_code
  5. '''
  6. CSI = '\033['
  7. OSC = '\033]'
  8. BEL = '\007'
  9. def code_to_chars(code):
  10. return CSI + str(code) + 'm'
  11. def set_title(title):
  12. return OSC + '2;' + title + BEL
  13. def clear_screen(mode=2):
  14. return CSI + str(mode) + 'J'
  15. def clear_line(mode=2):
  16. return CSI + str(mode) + 'K'
  17. class AnsiCodes(object):
  18. def __init__(self):
  19. # the subclasses declare class attributes which are numbers.
  20. # Upon instantiation we define instance attributes, which are the same
  21. # as the class attributes but wrapped with the ANSI escape sequence
  22. for name in dir(self):
  23. if not name.startswith('_'):
  24. value = getattr(self, name)
  25. setattr(self, name, code_to_chars(value))
  26. class AnsiCursor(object):
  27. def UP(self, n=1):
  28. return CSI + str(n) + 'A'
  29. def DOWN(self, n=1):
  30. return CSI + str(n) + 'B'
  31. def FORWARD(self, n=1):
  32. return CSI + str(n) + 'C'
  33. def BACK(self, n=1):
  34. return CSI + str(n) + 'D'
  35. def POS(self, x=1, y=1):
  36. return CSI + str(y) + ';' + str(x) + 'H'
  37. class AnsiFore(AnsiCodes):
  38. BLACK = 30
  39. RED = 31
  40. GREEN = 32
  41. YELLOW = 33
  42. BLUE = 34
  43. MAGENTA = 35
  44. CYAN = 36
  45. WHITE = 37
  46. RESET = 39
  47. # These are fairly well supported, but not part of the standard.
  48. LIGHTBLACK_EX = 90
  49. LIGHTRED_EX = 91
  50. LIGHTGREEN_EX = 92
  51. LIGHTYELLOW_EX = 93
  52. LIGHTBLUE_EX = 94
  53. LIGHTMAGENTA_EX = 95
  54. LIGHTCYAN_EX = 96
  55. LIGHTWHITE_EX = 97
  56. class AnsiBack(AnsiCodes):
  57. BLACK = 40
  58. RED = 41
  59. GREEN = 42
  60. YELLOW = 43
  61. BLUE = 44
  62. MAGENTA = 45
  63. CYAN = 46
  64. WHITE = 47
  65. RESET = 49
  66. # These are fairly well supported, but not part of the standard.
  67. LIGHTBLACK_EX = 100
  68. LIGHTRED_EX = 101
  69. LIGHTGREEN_EX = 102
  70. LIGHTYELLOW_EX = 103
  71. LIGHTBLUE_EX = 104
  72. LIGHTMAGENTA_EX = 105
  73. LIGHTCYAN_EX = 106
  74. LIGHTWHITE_EX = 107
  75. class AnsiStyle(AnsiCodes):
  76. BRIGHT = 1
  77. DIM = 2
  78. NORMAL = 22
  79. RESET_ALL = 0
  80. Fore = AnsiFore()
  81. Back = AnsiBack()
  82. Style = AnsiStyle()
  83. Cursor = AnsiCursor()