user_interface - Format coloured text to the terminal

Purpose:

This class module provides an interface to the Windows/Linux command line interfaces (CLI), enabling the user to easily print text, headings and banners in a variety of pre-defined (and customisable) colour layouts, to the terminal.

The callable printing methods in this module mean the user does not need to mess with ANSI escape sequences and other formatting overhead. Rather, just call the method and the overhead is taken care of.

This module contains a UserInterface class whose methods provide a standard way of reporting normal, alternative and abnormal behaviour. The following formats are built-in:

  • Fully customisable messages and headers via the print_() method.

  • The ability to print headings, such as:

    • black text on a cyan background

    • black text on a green background

    • black text on a white background

    • black text on a yellow background

    • white text on a blue background

    • etc …

  • User input expected: as white text on a black background

  • Normal behaviour: as green text on a black background

  • Alternative behaviour: (e.g. a warning) as yellow text on a black background

  • Abnormal or erroneous behaviour: as red text on a black background

Platform:

Linux/Windows | Python 3.7+

Developer:

M Critchard, J Berendt

Email:

support@s3dev.uk

Example:

For usage examples, please refer to the following class docstrings:

class user_interface.PrintBanner(name: str = None, version: str = None, desc: str = None, info: dict = None, chars: int = 72, ribbon: str = '-', fore: str = 'brightwhite', back: str = 'black', style: str = 'normal')[source]

This class is used to print an information banner to the terminal.

Generally, this class is used in the startup routine of an application to display information about the application. For example, information such as the application title, version, security classification, etc.

Design:

This may be useful if you want to use a ‘standardised’ program header across all of your programs. This class can be called in the program’s startup routine.

The banner can also be used to display and report expected error information. For example, if a certain validation type of error is expected, a customised version of this banner can wrap the error information such as error type, the issue, the file name/location, and the resolution.

For further detail, refer to the Design and Parameters sections of the __init__() method, as the banner is highly configurable.

Example Banner:

Below is a printed example of a program header banner:

------------------------------------------------------------
Program     :    Spam and Eggs
Version     :    2.0.3

Description :    The complete spam and eggs recipe guide.
------------------------------------------------------------
Example Code:

This code can be used to print the banner above:

>>> from utils4.user_interface import PrintBanner

>>> PrintBanner(name='Spam and Eggs',
                version='2.0.3',
                desc='The complete spam and eggs recipe guide.')
__init__(name: str = None, version: str = None, desc: str = None, info: dict = None, chars: int = 72, ribbon: str = '-', fore: str = 'brightwhite', back: str = 'black', style: str = 'normal')[source]

Display a configurable information banner to the terminal.

Parameters:
  • name (str, optional) – Name of your program. Defaults to None.

  • version (str, optional) – The program’s version number. Defaults to None.

  • desc (str, optional) – Description of what your program is all about. Defaults to None.

  • info (list, optional) –

    A list of dictionaries containing the fields to be used. Defaults to None.

    The info parameter is used to generate a completely customised banner. Essentially, whatever key/value pairs you pass in, are what will be printed in the banner.

    Hint

    For example, this info parameter:

    >>> info = [{'Program':'Spam and Eggs'},
    >>>         {'Version':'2.0.3'},
    >>>         {'':''},  # Gives an empty line.
    >>>         {'Description':'The complete spam and eggs recipe guide.'},
    >>>         {'Comments':'They're even better in green!'}]
    
    >>> PrintBanner(info=info)
    

    … will print the banner:

    ------------------------------------------------------------------------
     Program        :    Spam and Eggs
     Version        :    2.0.3
    
     Description    :    The complete spam and eggs recipe guide.
     Comments       :    They're even better in green!
    ------------------------------------------------------------------------
    

  • chars (int, optional) – In the number of characters, the size of the buffer used for the background colour, and the length of the ribbon. Defaults to 72.

  • ribbon (str, optional) – The character(s) to use for the ribbon. If multiple characters are passed into this parameter, these characters will be repeated until the length of the chars parameter is met. Defaults to '-'.

  • fore (str, optional) – Text colour. The eight basic colour names are accepted as strings. Defaults to ‘brightwhite’.

  • back (str, optional) – Background colour. The eight basic colour names are accepted as strings. Defaults to ‘black’.

  • style (str, optional) –

    Style of the text. Defaults to ‘normal’.

    Options:
    • dim

    • bold

    • normal

    • underline

Design:

In short, if the info parameter is left as None, a default banner is generated using the values passed into the name, version and desc parameters.

The string templates used for the banner layout may be configured in this module’s private _Config class.

Additional configuration is available through the other parameters, which are all defined in the Parameters section above.

Also, the title of the console window is updated to show the program’s name and version, if all of the following criteria are met:

  • Windows OS

  • name parameter is not None

  • version parameter is not None

Example:

The following code block:

>>> from utils4.user_interface import PrintBanner

>>> PrintBanner(name='Spam and Eggs',
                version='2.0.3',
                desc='The complete spam and eggs guide.',
                chars=55,
                ribbon='~-',
                fore='brightyellow',
                back='black',
                style='normal')

… will print this banner in yellow text on a black background:

~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
 Program        :    Spam and Eggs
 Version        :    2.0.3

 Description    :    The complete spam and eggs guide.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
class user_interface.UserInterface[source]

This class encapsulates the Linux/Windows command line interfaces and provides a standard way of reporting normal, alternative and abnormal behaviour.

Example:

Below are a couple of examples showing how easy it is to print coloured text to the terminal.

To print a green text to the console:

>>> from utils4.user_interface import ui

>>> ui.print_(text='Some text ...', fore='green', style='normal')

To print a blue text on a white background to the console:

>>> from utils4.user_interface import ui

>>> ui.print_(text='Some text ...', fore='blue', back='white', style='normal')

To print a green header to the console:

>>> from utils4.user_interface import ui

>>> ui.print_heading_green(text='Header for a section of output')
__init__()[source]

UserInterface class initialiser.

  • Purpose:

    If Windows is detected as the system’s OS, the utils4.__init__ module initialises the colorama library, which enables the user to print coloured text to the Windows terminal.

  • Background on win_unicode_console:

    The win_unicode_console library is used here to fix a problem between the Python input() function and the Windows CLI. The problem causes ANSI characters to be displayed to the terminal, rather than setting colours.

  • Background on colorama:

    The colorama library is initialised to:

    ‘strip ANSI characters from stdout and convert them into the equivalent win32 calls.’

    —Jonathan Hartley, creator of colorama.

    The Win32 console (excluding some later versions of Win10) does not support ANSI escape sequences, and therefore (unlike UNIX and Unix-like systems) simply printing the escape sequence to the native Windows CLI with the text does not work. To address this, we use the colorama library for the low-level Win32 work. Thanks Jonathan!

Note

It may be possible to remove use of win_unicode_console in later versions of Python, possibly 3.6+.

get_input(prompt: str, fore: str = 'white', back: str = 'black', style: str = 'normal', ending_char: str = '', add_space: bool = True)[source]

Deprecated version of the new method: prompt().

Warning

This method has been deprecated.

print_(text: str, fore: str = 'brightwhite', back: str = 'black', style: str = 'normal', h_pad: int = 0, v_pad: int = 0, sleep: float = 0.0)[source]

Wrap the built-in print() function to provide colour customisation.

Parameters:
  • text (str) – The text to be printed to the terminal.

  • fore (str, optional) – The text colour. Defaults to ‘brightwhite’.

  • back (str, optional) – Background colour. Defaults to ‘black’.

  • style (str, optional) – ANSI style selector. Defaults to ‘normal.’

  • h_pad (int, optional) –

    The amount of horizontal padding, in characters. This option will increase the field size to the value of h_pad and add (n) blank characters of background colour after the text string. If greater than the number of text characters, colour will extend past the end of the text. Defaults to 0.

    Note

    The h_pad value is a field size value, not the number of spaces past the end of the text string.

  • v_pad (int, optional) – The amount of vertical padding, in lines. This option will add (n) blank lines of backgound colour above and below the text string, acting like a banner. The banner will extend to the number of spaces specified in the h_pad parameter. Defaults to 0.

  • sleep (float, optional) – Number of seconds to pause the program after a message or banner is printed. Although the default sleep value is 0 seconds, the default changes to (n) second, if the v_pad parameter is > 0. This provides a default pause for the user to read the banner. The default v_pad sleep time can be updated in this module’s private _Config class. Defaults to 0.

Colour and Style Options:

  • fore / back

    black, blue, cyan, green, magenta, red, white, yellow, brightblack, brightblue, brightcyan, brightgreen, brightmagenta, brightred, brightwhite, brightyellow

  • style

    bold, dim, normal, underline

Design:

This method extends the functionality of the built-in print() function by adding the options for text/background colouring and padding. The user can pass specific text/background colours along with a style and horizontal and vertical padding.

The colour and style strings are implemented using ANSI escape sequences, which are added to the text string.

In addition to colour, horizontal and vertical padding are available.

After a message or banner is printed, the sleep timer can be called to pause the program for (n) seconds, for the user to read the message or banner. If the v_pad value is > 0, and the sleep value is 0, the sleep timer value is overridden with the value defined in this module’s private _Config class, under the v_pad_sleep key.

For further detail, refer to the Parameters section of this docstring, and refer to the Colour and Style Options section for each string parameter’s available options.

print_alert(text: str, style: str = 'normal')[source]

Print red text on a black background.

Parameters:
  • text (str) – Text to be printed.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

static print_blank_lines(quantity: int = 1)[source]

Print (n) blank lines.

Parameters:

qualtity (int, optional) – Number of blank lines to print. Defaults to 1.

static print_error(error: object)[source]

Print red error text on a black background.

Parameters:

error (object) – This is the error object generated by the Exception.

This method calls the reporterror() method to generate the error message.

Example:

To print an error message:

>>> from utils4.user_interface import ui

>>> try:
>>>     1/0
>>> except Exception as err:
>>>     ui.print_error(error=err)

ERROR:  division by zero
TYPE:   <class 'ZeroDivisionError'>
MODU:   /tmp/ipykernel_27103/573922745.py
FUNC:   <module>
LINE:   2
CMD:    1/0
print_error_unexpected()[source]

Print red ‘unexpected error’ text on black background.

Design:

This method uses the call stack to print a message for ‘unexpected error’ errors.

print_heading_blue(text: str, fore: str = 'brightwhite', style: str = 'normal', padto: int = 0)[source]

Print white text on a blue background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘brightwhite’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_heading_cyan(text: str, fore: str = 'black', style: str = 'normal', padto: int = 0)[source]

Print black text on a cyan background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘black’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_heading_green(text: str, fore: str = 'black', style: str = 'normal', padto: int = 0)[source]

Print black text on a green background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘black’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_heading_red(text: str, fore: str = 'black', style: str = 'normal', padto: int = 0)[source]

Print black text on a red background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘black’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_heading_white(text: str, fore: str = 'black', style: str = 'normal', padto: int = 0)[source]

Print black text on a white background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘black’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_heading_yellow(text: str, fore: str = 'black', style: str = 'normal', padto: int = 0)[source]

Print black text on a yellow background.

Parameters:
  • text (str) – Text to be printed.

  • fore (str, optional) – Text colour. Defaults to ‘black’.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

  • padto (int, optional) – Padding width, as number of characters. Defaults to 0.

print_normal(text: str, style: str = 'normal')[source]

Print green text on a black background.

Parameters:
  • text (str) – Text to be printed.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

print_warning(text: str, style: str = 'normal')[source]

Print yellow text on a black background.

Parameters:
  • text (str) – Text to be printed.

  • style (str, optional) – Style to be used. Defaults to ‘normal’.

prompt(text: str, fore: str = 'brightwhite', back: str = 'black', style: str = 'normal', ending_char: str = '', add_space: bool = True)[source]

Get user input via a CLI prompt formatted by the caller.

This method extends the built-in input() function (although not used by this method) by adding appearance control and text colouring. Like the input() function, the user’s input is returned to the caller as a str type.

Parameters:
  • text (str) – The text to be displayed.

  • fore (str, optional) – Text colour. Defaults to ‘brightwhite’.

  • back (str, optional) – Background colour. Defaults to ‘black’.

  • style (str, optional) – The ‘normal’ style selects the 8 original foreground colours (SGR 30-37). The ‘bright’ style provides access to the 8 additional foreground colours (SGR 90-97). Defaults to ‘normal’.

  • ending_char (str, optional) – Character to be added to the end of the prompt. If the user’s input should be on a new line, pass \n into this parameter. Defaults to ''.

  • add_space (bool, optional) – Add a space separator between the prompt and the user’s input. Defaults to True.

Colour and Style Options:

  • fore / back

    black, blue, cyan, green, magenta, red, white, yellow, brightblack, brightblue, brightcyan, brightgreen, brightmagenta, brightred, brightwhite, brightyellow

  • style

    bold, dim, normal, underline

Example:

To use the prompt in its standard form:

>>> inp = ui.prompt('Enter a number:')

Enter a number: 73

>>> inp
'73'

Request user input in red text:

>>> inp = ui.prompt('Enter a number:', fore='brightred')

Enter a number: 13

>>> inp
'13'

Request user input in red text in a new line:

>>> inp = ui.prompt('An unnecessarily long prompt requesting a number:',
                    fore='brightred',
                    ending_char='\n',
                    add_space=False)

An unnecessarily long prompt requesting a number:
37

>>> inp
'37'
class user_interface._Config[source]

Storage class for the module’s config items.

custom_string = ' {key:{pad}}:{spaces}{val}'
default_string = ' {title:{pad}}:{spaces}{name}'
v_pad_sleep = 1