Coverage for /var/devmt/py/utils4_1.8.0/utils4/termcolour.py: 100%
48 statements
« prev ^ index » next coverage.py v7.6.9, created at 2025-08-26 21:39 +0100
« prev ^ index » next coverage.py v7.6.9, created at 2025-08-26 21:39 +0100
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4:Purpose: This module contains basic and bright (16 colours) text and
5 background ANSI colour codes for colouring Linux and Windows
6 terminal output.
8:Developer: J Berendt
9:Email: support@s3dev.uk
11:Comments: If used on Windows, the ``colorama.init()`` method is
12 called by the ``utils4.__init__`` module to configure Windows
13 to handle CLI colouring.
15:Example:
17 Print red text to the terminal::
19 >>> from utils4.termcolour import Text
21 >>> print(f'{Text.RED}ALERT! This is red text.{Text.RESET}')
22 ALERT! This is red text.
25 Print red text on a white background to the terminal::
27 >>> from utils4.termcolour import Back, Text
29 >>> print(f'{Text.RED}{Back.BRIGHTWHITE}ALERT! This is red text on white.{Text.RESET}')
30 ALERT! This is red text on white.
33 Print bold yellow text on a black background to the terminal::
35 >>> from utils4.termcolour import Back, Text, Style
37 >>> print(f'{Text.YELLOW}{Back.BLACK}{Style.BOLD}Bold yellow text.{Text.RESET}')
38 Bold yellow text.
40"""
41# pylint: disable=too-few-public-methods
44class _AnsiBase:
45 """Generic base ANSI colours class.
47 The colours for each class are dynamically created as class attributes
48 by the initialiser of this base class.
50 """
52 RESET = 0
54 def __init__(self):
55 """ANSI generic base class initialiser."""
56 for i in self.__dir__():
57 if not i.startswith('_'):
58 self.__setattr__(i, f'\033[{self.__getattribute__(i)}m')
61class AnsiBack(_AnsiBase):
62 """ANSI background colour codes.
64 Note:
65 The bright colours have been included, but are not always supported.
67 """
69 BLACK = 40
70 RED = 41
71 GREEN = 42
72 YELLOW = 43
73 BLUE = 44
74 MAGENTA = 45
75 CYAN = 46
76 WHITE = 47
77 BRIGHTBLACK = 100
78 BRIGHTRED = 101
79 BRIGHTGREEN = 102
80 BRIGHTYELLOW = 103
81 BRIGHTBLUE = 104
82 BRIGHTMAGENTA = 105
83 BRIGHTCYAN = 106
84 BRIGHTWHITE = 107
86class AnsiStyle(_AnsiBase):
87 """ANSI style codes."""
89 BOLD = 1
90 DIM = 2
91 UNDERLINE = 4
92 NORMAL = 22
95class AnsiText(_AnsiBase):
96 """ANSI foreground (text) colour codes.
98 Note:
99 The bright colours have been included, but are not always supported.
101 """
103 BLACK = 30
104 RED = 31
105 GREEN = 32
106 YELLOW = 33
107 BLUE = 34
108 MAGENTA = 35
109 CYAN = 36
110 WHITE = 37
111 BRIGHTBLACK = 90
112 BRIGHTRED = 91
113 BRIGHTGREEN = 92
114 BRIGHTYELLOW = 93
115 BRIGHTBLUE = 94
116 BRIGHTMAGENTA = 95
117 BRIGHTCYAN = 96
118 BRIGHTWHITE = 97
121Text = AnsiText()
122Back = AnsiBack()
123Style = AnsiStyle()