Revision 1490a90c qa/colors.py

b/qa/colors.py
22 22
"""Script for adding colorized output to Ganeti.
23 23

  
24 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".)
25 26

  
26 27
"""
27 28

  
28 29
import os
30
import subprocess
29 31
import sys
30 32

  
31 33
DEFAULT = '\033[0m'
......
47 49
    return color + line + DEFAULT
48 50
  else:
49 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)

Also available in: Unified diff