1 # Copyright (c) 2011 The Chromium OS Authors.
3 # SPDX-License-Identifier: GPL-2.0+
8 This module handles terminal interaction including ANSI color codes.
14 # Selection of when we want our output to be colored
15 COLOR_IF_TERMINAL, COLOR_ALWAYS, COLOR_NEVER = range(3)
18 """Conditionally wraps text in ANSI color escape sequences."""
19 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
21 BRIGHT_START = '\033[1;%dm'
22 NORMAL_START = '\033[22;%dm'
23 BOLD_START = '\033[1m'
26 def __init__(self, colored=COLOR_IF_TERMINAL):
27 """Create a new Color object, optionally disabling color output.
30 enabled: True if color output should be enabled. If False then this
31 class will not add color codes at all.
34 self._enabled = (colored == COLOR_ALWAYS or
35 (colored == COLOR_IF_TERMINAL and
36 os.isatty(sys.stdout.fileno())))
40 def Start(self, color, bright=True):
41 """Returns a start color code.
44 color: Color to use, .e.g BLACK, RED, etc.
47 If color is enabled, returns an ANSI sequence to start the given
48 color, otherwise returns empty string
51 base = self.BRIGHT_START if bright else self.NORMAL_START
52 return base % (color + 30)
56 """Retruns a stop color code.
59 If color is enabled, returns an ANSI color reset sequence,
60 otherwise returns empty string
66 def Color(self, color, text, bright=True):
67 """Returns text with conditionally added color escape sequences.
70 color: Text color -- one of the color constants defined in this
72 text: The text to color.
75 If self._enabled is False, returns the original text. If it's True,
76 returns text with color escape sequences based on the value of
81 if color == self.BOLD:
82 start = self.BOLD_START
84 base = self.BRIGHT_START if bright else self.NORMAL_START
85 start = base % (color + 30)
86 return start + text + self.RESET