1# -*- coding: utf-8 -*- 2# Copyright (c) 2011 The Chromium OS Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Terminal utilities 7 8This module handles terminal interaction including ANSI color codes. 9""" 10 11from __future__ import print_function 12 13 14class Color(object): 15 """Conditionally wraps text in ANSI color escape sequences.""" 16 17 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) 18 BOLD = -1 19 COLOR_START = '\033[1;%dm' 20 BOLD_START = '\033[1m' 21 RESET = '\033[0m' 22 23 24 def __init__(self, enabled): 25 """Create a new Color object, optionally disabling color output. 26 27 Args: 28 enabled: True if color output should be enabled. If False then this 29 class will not add color codes at all. 30 """ 31 self._enabled = enabled 32 33 34 def Start(self, color): 35 """Returns a start color code. 36 37 Args: 38 color: Color to use, .e.g BLACK, RED, etc. 39 40 Returns: 41 If color is enabled, returns an ANSI sequence to start the given color, 42 otherwise returns empty string 43 """ 44 if self._enabled: 45 return self.COLOR_START % (color + 30) 46 return '' 47 48 49 def Stop(self): 50 """Returns a stop color code. 51 52 Returns: 53 If color is enabled, returns an ANSI color reset sequence, otherwise 54 returns empty string 55 """ 56 if self._enabled: 57 return self.RESET 58 return '' 59 60 def Color(self, color, text): 61 """Returns text with conditionally added color escape sequences. 62 63 Keyword arguments: 64 color: Text color -- one of the color constants defined in this class. 65 text: The text to color. 66 67 Returns: 68 If self._enabled is False, returns the original text. If it's True, 69 returns text with color escape sequences based on the value of color. 70 """ 71 if not self._enabled: 72 return text 73 if color == self.BOLD: 74 start = self.BOLD_START 75 else: 76 start = self.COLOR_START % (color + 30) 77 return start + text + self.RESET 78