terminal.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0+
  4. #
  5. """Terminal utilities
  6. This module handles terminal interaction including ANSI color codes.
  7. """
  8. import os
  9. import sys
  10. # Selection of when we want our output to be colored
  11. COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
  12. class Color(object):
  13. """Conditionally wraps text in ANSI color escape sequences."""
  14. BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
  15. BOLD = -1
  16. BRIGHT_START = '\033[1;%dm'
  17. NORMAL_START = '\033[22;%dm'
  18. BOLD_START = '\033[1m'
  19. RESET = '\033[0m'
  20. def __init__(self, colored=COLOR_IF_TERMINAL):
  21. """Create a new Color object, optionally disabling color output.
  22. Args:
  23. enabled: True if color output should be enabled. If False then this
  24. class will not add color codes at all.
  25. """
  26. self._enabled = (colored == COLOR_ALWAYS or
  27. (colored == COLOR_IF_TERMINAL and os.isatty(sys.stdout.fileno())))
  28. def Start(self, color, bright=True):
  29. """Returns a start color code.
  30. Args:
  31. color: Color to use, .e.g BLACK, RED, etc.
  32. Returns:
  33. If color is enabled, returns an ANSI sequence to start the given
  34. color, otherwise returns empty string
  35. """
  36. if self._enabled:
  37. base = self.BRIGHT_START if bright else self.NORMAL_START
  38. return base % (color + 30)
  39. return ''
  40. def Stop(self):
  41. """Retruns a stop color code.
  42. Returns:
  43. If color is enabled, returns an ANSI color reset sequence,
  44. otherwise returns empty string
  45. """
  46. if self._enabled:
  47. return self.RESET
  48. return ''
  49. def Color(self, color, text, bright=True):
  50. """Returns text with conditionally added color escape sequences.
  51. Keyword arguments:
  52. color: Text color -- one of the color constants defined in this
  53. class.
  54. text: The text to color.
  55. Returns:
  56. If self._enabled is False, returns the original text. If it's True,
  57. returns text with color escape sequences based on the value of
  58. color.
  59. """
  60. if not self._enabled:
  61. return text
  62. if color == self.BOLD:
  63. start = self.BOLD_START
  64. else:
  65. base = self.BRIGHT_START if bright else self.NORMAL_START
  66. start = base % (color + 30)
  67. return start + text + self.RESET