Belle II Software development
ANSIColors Class Reference
Inheritance diagram for ANSIColors:

Public Member Functions

 convert_color (cls, color)
 
 color (cls, foreground=None, background=None, bold=False, underline=False, inverted=False)
 
 fg (cls, color)
 
 bg (cls, color)
 
 reset (cls)
 

Static Public Member Functions

 supported ()
 

Detailed Description

Simple class to handle color output to the terminal.

This class allows to very easily add color output to the terminal

>>> from terminal_utils import ANSIColors as ac
>>> print(f"{ac.fg('red')}Some text in {ac.color(underline=True)}RED{ac.reset()}")

The basic colors can be specified by name (case insensitive) or by enum value.
Custom colors can be supplied using hex notation like ``#rgb`` or ``#rrggbb``
(Hint: ``matplotlib.colors.to_hex`` might be useful here). As an example to
use the viridis colormap to color the output on the terminal::

    from matplotlib import cm
    from matplotlib.colors import to_hex
    from terminal_utils import ANSIColors as ac

    # sample the viridis colormap at 16 points
    for i in range(16):
        # convert i to be in [0..1] and get the hex color
        color = to_hex(cm.viridis(i/15))
        # and print the hex color in the correct color
        print(f"{i}. {ac.fg(color)}{color}{ac.reset()}")


If the output is not to a terminal color output will be disabled and nothing
will be added to the output, for example when redirecting the output to a
logfile.

Definition at line 33 of file terminal_utils.py.

Member Function Documentation

◆ bg()

bg ( cls,
color )
Shorthand for `color(background=color) <color>`

Definition at line 149 of file terminal_utils.py.

149 def bg(cls, color):
150 """Shorthand for `color(background=color) <color>`"""
151 return cls.color(background=color)
152

◆ color()

color ( cls,
foreground = None,
background = None,
bold = False,
underline = False,
inverted = False )
Change terminal colors to the given foreground/background colors and attributes.

This will return a string to be printed to change the color on the terminal.
To revert to default print the output of `reset()`

Parameters:
    foreground (int or str): foreground color to use, can be any value accepted by `convert_color`
                             If None is given the current color will not be changed.
    background (int or str): background color to use, can be any value accepted by `convert_color`.
                             If None is given the current color will not be changed.
    bold (bool): Use bold font
    underline (bool): Underline the text
    inverted (bool): Flip background and foreground color

Definition at line 109 of file terminal_utils.py.

109 def color(cls, foreground=None, background=None, bold=False, underline=False, inverted=False):
110 """
111 Change terminal colors to the given foreground/background colors and attributes.
112
113 This will return a string to be printed to change the color on the terminal.
114 To revert to default print the output of `reset()`
115
116 Parameters:
117 foreground (int or str): foreground color to use, can be any value accepted by `convert_color`
118 If None is given the current color will not be changed.
119 background (int or str): background color to use, can be any value accepted by `convert_color`.
120 If None is given the current color will not be changed.
121 bold (bool): Use bold font
122 underline (bool): Underline the text
123 inverted (bool): Flip background and foreground color
124 """
125 if not cls.supported():
126 return ""
127
128 codes = []
129 if foreground is not None:
130 codes.append(f"38;{cls.convert_color(foreground)}")
131 if background is not None:
132 codes.append(f"48;{cls.convert_color(background)}")
133 if bold:
134 codes.append(1)
135 if underline:
136 codes.append(4)
137 if inverted:
138 codes.append(7)
139 if not codes:
140 return ""
141 return f"\x1b[{';'.join(map(str, codes))}m"
142

◆ convert_color()

convert_color ( cls,
color )
Convert a color to the necessary ansi code. The argument can either bei

* an integer corresponding to the ansi color (see the enum values of this class)
* the name (case insensitive) of one of the enum values of this class
* a hex color code of the form ``#rgb`` or ``#rrggbb``

Raises:
    KeyError: if the argument is a string not matching to one of the known colors

Definition at line 85 of file terminal_utils.py.

85 def convert_color(cls, color):
86 """Convert a color to the necessary ansi code. The argument can either bei
87
88 * an integer corresponding to the ansi color (see the enum values of this class)
89 * the name (case insensitive) of one of the enum values of this class
90 * a hex color code of the form ``#rgb`` or ``#rrggbb``
91
92 Raises:
93 KeyError: if the argument is a string not matching to one of the known colors
94 """
95 if isinstance(color, str):
96 if color[0] == '#':
97 if len(color) == 4:
98 r, g, b = (int(e, 16)*17 for e in color[1:])
99 else:
100 r, g, b = (int(color[i:i+2], 16) for i in [1, 3, 5])
101 return f"2;{r};{g};{b}"
102 try:
103 color = cls[color.upper()].value
104 except KeyError as e:
105 raise KeyError(f"Unknown color: '{color}'") from e
106 return f"5;{color}"
107

◆ fg()

fg ( cls,
color )
Shorthand for `color(foreground=color) <color>`

Definition at line 144 of file terminal_utils.py.

144 def fg(cls, color):
145 """Shorthand for `color(foreground=color) <color>`"""
146 return cls.color(foreground=color)
147

◆ reset()

reset ( cls)
Reset colors to default

Definition at line 154 of file terminal_utils.py.

154 def reset(cls):
155 """Reset colors to default"""
156 return '\x1b[0m' if cls.supported() else ''
157
158

◆ supported()

supported ( )
static
Check whether the output is a terminal.

If this is False, the methods `color`, `fg`, `bg` and `reset` will only
return an empty string as color output will be disabled

Definition at line 75 of file terminal_utils.py.

75 def supported():
76 """
77 Check whether the output is a terminal.
78
79 If this is False, the methods `color`, `fg`, `bg` and `reset` will only
80 return an empty string as color output will be disabled
81 """
82 return sys.stdout.isatty()
83

The documentation for this class was generated from the following file: