root / qa / colors.py @ 1490a90c
History | View | Annotate | Download (1.9 kB)
1 |
#!/usr/bin/python -u
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2013 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Script for adding colorized output to Ganeti.
|
23 |
|
24 |
Colors are enabled only if the standard output is a proper terminal.
|
25 |
(Or call check_for_colors() to make a thorough test using "tput".)
|
26 |
|
27 |
"""
|
28 |
|
29 |
import os |
30 |
import subprocess |
31 |
import sys |
32 |
|
33 |
DEFAULT = '\033[0m'
|
34 |
RED = '\033[91m'
|
35 |
GREEN = '\033[92m'
|
36 |
BLUE = '\033[94m'
|
37 |
CYAN = '\033[96m'
|
38 |
WHITE = '\033[97m'
|
39 |
YELLOW = '\033[93m'
|
40 |
MAGENTA = '\033[95m'
|
41 |
GREY = '\033[90m'
|
42 |
BLACK = '\033[90m'
|
43 |
|
44 |
_enabled = sys.stdout.isatty() |
45 |
|
46 |
|
47 |
def colorize(line, color=None): |
48 |
if _enabled and color is not None: |
49 |
return color + line + DEFAULT
|
50 |
else:
|
51 |
return line
|
52 |
|
53 |
|
54 |
def check_for_colors(): |
55 |
"""Tries to call 'tput' to properly determine, if the terminal has colors.
|
56 |
|
57 |
This functions is meant to be run once at the program's start. If not
|
58 |
invoked, colors are enabled iff standard output is a terminal.
|
59 |
"""
|
60 |
colors = 0
|
61 |
if sys.stdout.isatty():
|
62 |
try:
|
63 |
p = subprocess.Popen(["tput", "colors"], stdout=subprocess.PIPE) |
64 |
output = p.communicate()[0]
|
65 |
if p.returncode == 0: |
66 |
colors = int(output)
|
67 |
except (OSError, ValueError): |
68 |
pass
|
69 |
global _enabled
|
70 |
_enabled = (colors >= 2)
|