Skip to main content

A package for formatted console output using ANSI escape codes - colors and formatting.

Project description

This library allows you to set the foreground and background colors and style of your Console output. The script uses ANSI Escape Codes for colors and allows you to create custom colors that are also passed as ANSI Escape Codes. The script also uses the ANSI Escape Codes for styles bold, underline, and both combined. Coders can either put together a multi-formatted message or simply set the format for a single print() message.

This library also exposes some functionality that allows you to print WARNING, ERROR, and INFO messages or to print an Exception's stacktrace as an ERROR. This helps when you're using other 3rd-party libraries that are very verbose, and you cannot turn off their output. Meanwhile you're crossing your eyes trying to find Exception messages like 'was that an Exception? It was kinda shaped like an exception message...' Now we can make your Exception red!

OS COMPATIBILITY

Though Linux and Mac are pretty much always compatible... This library seamlessly takes into account Windows machines that are not necessarily configured to support ANSI escape codes. When your script runs, the library attempts to enable this feature for this session. If you're already compatible, we go formatted. If we can make you compatible for this session, we go formatted. If all fails, then we go back to printing with default behavior.

HOW TO REFERENCE

  1. install the library
    pip install formatted-console-output
  1. At the top of your script add the following import statements as needed:
    import formatted_console_output as fmt
    from formatted_console_output import output_formatted_message as print, output_many_format_message as printf
    from formatted_console_output import output_error_message as msg, log_exception_stacktrace as err

CODE COMPATIBILITY & OVERLOADING/ALIASING

I have found it easiest mentally to alias each method as shown in the imports above. You do not have to alias the method imports this way but that makes it more natural for you to code against and allows you to leverage everything else about the print() method. The script passes on all extra keyword arguments that are normally used in a print() call, so go wild.

Using the alias 'print' does NOT interfere with any other scripts. Any code referencing this library's output method as 'print' that then tries to use the print() method normally would still get the expected behavior.

HOW TO USE IN CODE

Methods Exposed in this Library

  • output_formatted_message() - Replaces print. Takes a message and a print() method's kwargs along with your added format and colors
  • output_many_format_message() - Prints an array of FormattedPhrase objects. Also takes a print() method's kwargs
  • output_error_message() - Prints a message as ERROR, WANRING, or INFO. Also takes a print() method's kwargs
  • log_exception_stacktrace() - Prints an Exception including the stacktrace as ERROR. Also takes a print() method's kwargs

Keyword Arguments for This Library (kwargs)

The added keyword arguments are:

  • fg_color (default is ForegroundColor.NONE)
  • bg_color (default is BackgroundColor.NONE)
  • format (default is TextFormat.NONE)
Enumerators & Classes

The enumerators/classes that define these colors/formats are:

  • ForegroundColor [BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, NONE]
  • BackgroundColor [BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, NONE]
  • TextFormat [BOLD, UNDERLINE, BOLD_AND_UNDERLINE, NONE]
  • ErrorType [INFO, WARNING, ERROR]
  • CustomColor - any RGB as a fg_color or bg_color
    • Parameters in constructor: int:r, int:g, int:b, bool:is_fg
    • Can be passed as an argument in place of BackgroundColor or ForegroundColor
  • FormattedPhrase() - an individually formatted piece of text that can be joined to others
    • Parameters in constructor: str:string_phrase, enum:bg_color, enum:fg_color, enum:format
    • Methods/Functions:
      • get_output() - returns the string_phrase with all escape codes embedded

NOTE: parameters bg_color and fg_color in any method can take either an Enumerator value (BackgroundColor, ForeGroundColor) or a CustomColor object.

CODE EXAMPLES

Example 1: Format one line of text

In the following example we're printing a message to console with one format for the entire line: blue text on a yellow background in bold style. I also threw in some standard keyword arguments (sep and end) to show that can be included:

    import formatted_console_output as fmt
    from formatted_console_output import output_formatted_message as print

    print(
        f"Archiving files and reporting against them in '{dir_path}'",
        fg_color=fmt.ForegroundColor.BLUE,
        bg_color=fmt.BackgroundColor.YELLOW,
        format=fmt.TextFormat.BOLD,
        sep="  -  ",
        end="\n\n",
    )

Example 2: Use a CustomColor

In this example, we're passing a CustomColor which is a brown color for bg_color. So this will print yellow on brown:

    import formatted_console_output as fmt
    from formatted_console_output import output_formatted_message as print

    print(
        "The quick brown foo jumped over the lazy bar",
        fg_color=fmt.ForegroundColor.YELLOW,
        bg_color=fmt.CustomColor(r=156, g=101, b=0, is_fg=False),
    )

Example 3: Multiple formats in a single message using FormattedPhrase

In this example we're formatting each phrase differently and putting it together using an array of FormattedPhrase objects:

Note: any left out parameter in any FormattedPhrase object is considered to be set to NONE

    import formatted_console_output as fmt
    from formatted_console_output import  output_many_format_message as printf

    #create an array of FormattedPhrase objects to pass to printf()
    message = [
        fmt.FormattedPhrase(
            "The ",
            bg_color=fmt.BackgroundColor.BLACK,
            fg_color=fmt.ForegroundColor.YELLOW,
            format=fmt.TextFormat.UNDERLINE,
        ),
        fmt.FormattedPhrase(
            "quick brown foo ",
            bg_color=fmt.BackgroundColor.RED,
            fg_color=fmt.ForegroundColor.YELLOW,
            format=fmt.TextFormat.BOLD,
        ),
        fmt.FormattedPhrase(
            "jumped over the ",
            fg_color=fmt.ForegroundColor.YELLOW,
        ),
        fmt.FormattedPhrase(
            "lazy ",
            bg_color=fmt.BackgroundColor.BLUE,
            fg_color=fmt.ForegroundColor.YELLOW,
        ),
        fmt.FormattedPhrase(
            "bar",
            bg_color=fmt.BackgroundColor.BLUE,
            fg_color=fmt.ForegroundColor.YELLOW,
            format=fmt.TextFormat.BOLD_AND_UNDERLINE,
        ),
    ]
    printf(message)

Example 4: Combining multiple messages over time

In this example, we're not printing until later. First we're gathering formatted output by pulling a FormattedPhrase object's get_output() method into a variable. In essence, a coder could put together an entire formatted paragragh in memory over the course of the program's execution before printing at the end by doing something like this:

    import formatted_console_output as fmt
    from formatted_console_output import output_formatted_message as print

    message = ""
    #some code
    message += fmt.FormattedPhrase(
        "The ",
        bg_color=fmt.BackgroundColor.BLACK,
        fg_color=fmt.ForegroundColor.YELLOW,
        format=fmt.TextFormat.UNDERLINE,
    )
    #some more code
    message += fmt.FormattedPhrase(
        "quick brown foo ",
        bg_color=fmt.BackgroundColor.RED,
        fg_color=fmt.ForegroundColor.YELLOW,
        format=fmt.TextFormat.BOLD,
    )
    #some more code
    message += fmt.FormattedPhrase(
        "jumped over the ",
        bg_color=fmt.BackgroundColor.BLACK,
        fg_color=fmt.ForegroundColor.YELLOW,
    )
    #some more code
    message += fmt.FormattedPhrase(
        "lazy ",
        bg_color=fmt.BackgroundColor.BLUE,
        fg_color=fmt.ForegroundColor.YELLOW,
        format=fmt.TextFormat.BOLD,
    )
    #some more code
    message += fmt.FormattedPhrase(
        "bar",
        bg_color=fmt.BackgroundColor.BLUE,
        fg_color=fmt.ForegroundColor.YELLOW,
        format=fmt.TextFormat.BOLD_AND_UNDERLINE,
    )
    print(message)

Example 5: Printing an Exception with its Stacktrace

With log_exception_stacktrace() exposed in this library, you can intercept an Exception in a catch block (Except statement) and even get the full stacktrace back by doing something like this:

    from formatted_console_output import log_exception_stacktrace as err

    def func(a, b):
        raise Exception("This is a generic exception for testing purposes.")

    def main():
        try:
            a = None
            b = 1
            func(a, b)
        except Exception as e:
            err(e)

    main()

Example 6: Printing INFO, WANRING, and ERROR messages

With output_error_message() exposed, you can print messages as red (ERROR), yellow (WARNING), or cyan (INFO) by doing this:

    import formatted_console_output as fmt
    from formatted_console_output import output_error_message as msg

    msg("This is an Informational Message.", error_type=fmt.ErrorType.INFO)
    msg("This is a Warning Message.", error_type=fmt.ErrorType.WARNING)
    msg("This is an Error Message.", error_type=fmt.ErrorType.ERROR)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

formatted_console_output-0.4.1.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

formatted_console_output-0.4.1-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file formatted_console_output-0.4.1.tar.gz.

File metadata

File hashes

Hashes for formatted_console_output-0.4.1.tar.gz
Algorithm Hash digest
SHA256 39923eb8e5950c2dccd647e798575a8ba8225da7cdff274d5f60a1c566e20045
MD5 5b182fd4e18824379da43c2466b59d4a
BLAKE2b-256 caf7e809f59fa390b2cf361712ee42a24dfa319e39d78d946404f7654f98a8d2

See more details on using hashes here.

File details

Details for the file formatted_console_output-0.4.1-py3-none-any.whl.

File metadata

File hashes

Hashes for formatted_console_output-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8f842c646265482b2db7c81d0559ab23fc33a7211475e96cc4b1af162e5feb67
MD5 bb1625c40fc22dfb91fe138a6604703e
BLAKE2b-256 a1f210e08cefe4d78df7377f3310692629e81a06f217abcb7a195512e6fdadf0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page