Coverage for /var/devmt/py/utils4_1.6.0/utils4/termcolour.py: 100%
48 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-13 09:50 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-13 09:50 +0000
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:Platform: Linux/Windows | Python 3.7+
9:Developer: J Berendt
10:Email: support@s3dev.uk
12:Comments: If used on Windows, the ``colorama.init()`` method is
13 called by the ``utils4.__init__`` module to configure Windows
14 to handle CLI colouring.
16:Example:
18 Print red text to the terminal::
20 >>> from utils4.termcolour import Text
22 >>> print(f'{Text.RED}ALERT! This is red text.{Text.RESET}')
23 ALERT! This is red text.
26 Print red text on a white background to the terminal::
28 >>> from utils4.termcolour import Back, Text
30 >>> print(f'{Text.RED}{Back.BRIGHTWHITE}ALERT! This is red text on white.{Text.RESET}')
31 ALERT! This is red text on white.
34 Print bold yellow text on a black background to the terminal::
36 >>> from utils4.termcolour import Back, Text, Style
38 >>> print(f'{Text.YELLOW}{Back.BLACK}{Style.BOLD}Bold yellow text.{Text.RESET}')
39 Bold yellow text.
41"""
42# pylint: disable=too-few-public-methods
45class _AnsiBase:
46 """Generic base ANSI colours class.
48 The colours for each class are dynamically created as class attributes
49 by the initialiser of this base class.
51 """
53 RESET = 0
55 def __init__(self):
56 """ANSI generic base class initialiser."""
57 for i in self.__dir__():
58 if not i.startswith('_'):
59 self.__setattr__(i, f'\033[{self.__getattribute__(i)}m')
62class AnsiBack(_AnsiBase):
63 """ANSI background colour codes.
65 Note:
66 The bright colours have been included, but are not always supported.
68 """
70 BLACK = 40
71 RED = 41
72 GREEN = 42
73 YELLOW = 43
74 BLUE = 44
75 MAGENTA = 45
76 CYAN = 46
77 WHITE = 47
78 BRIGHTBLACK = 100
79 BRIGHTRED = 101
80 BRIGHTGREEN = 102
81 BRIGHTYELLOW = 103
82 BRIGHTBLUE = 104
83 BRIGHTMAGENTA = 105
84 BRIGHTCYAN = 106
85 BRIGHTWHITE = 107
87class AnsiStyle(_AnsiBase):
88 """ANSI style codes."""
90 BOLD = 1
91 DIM = 2
92 UNDERLINE = 4
93 NORMAL = 22
96class AnsiText(_AnsiBase):
97 """ANSI foreground (text) colour codes.
99 Note:
100 The bright colours have been included, but are not always supported.
102 """
104 BLACK = 30
105 RED = 31
106 GREEN = 32
107 YELLOW = 33
108 BLUE = 34
109 MAGENTA = 35
110 CYAN = 36
111 WHITE = 37
112 BRIGHTBLACK = 90
113 BRIGHTRED = 91
114 BRIGHTGREEN = 92
115 BRIGHTYELLOW = 93
116 BRIGHTBLUE = 94
117 BRIGHTMAGENTA = 95
118 BRIGHTCYAN = 96
119 BRIGHTWHITE = 97
122Text = AnsiText()
123Back = AnsiBack()
124Style = AnsiStyle()