Skip to content

console

XulbuX edited this page Oct 8, 2025 · 9 revisions

Console

This class includes methods for logging and other actions within the console.


Class Properties

A class property can be accessed with Console.<property name>.

w the current console width in text characters (if there's no console it returns the default console width 80)
h the current console height in lines (if there's no console it returns the default console height 24)
wh a tuple with the console size as (columns, lines) (if there's no console it returns the default console size (80, 24))
usr the current username


get_args()

This method is used to get the command arguments, for if the current file is run via the console as a command.
Params:

  • find_args: dict a dictionary that specifies where you are looking for which arguments and under which alias they should be returned
  • allow_spaces: bool = False whether to take spaces as separator of arg values or as part of an arg value

Returns: an Args object, with the specified aliases and two values per alias:

  1. exists is True if one of the listed arguments is found and False otherwise
  2. value is the value of the argument or a list of values for the "before" and "after" options (None if the argument has no value and [] if no "before" or "after" arguments were found)

Find Arguments:

The find_args parameter is a dictionary, where the keys specify under which alias the argument will be returned. The value of a key is one of the following options:

  • the literal "before" which looks for all non-flagged arguments before the first flagged argument (can only be used once)
  • the literal "after" which looks for all non-flagged arguments after the value of the last flagged argument (can only be used once)
  • a list of strings, which are the arg flags to look for (e.g. ["-f", "--file"])
  • a dictionary with the following keys:
    • flags (list[str]) the arg flags to look for (e.g. ["-f", "--file"])
    • default (Any) the default value of the argument if it is not found

Example:

If we want to be able to:

  • pass multiple filepaths without a flag
  • specify a config file
  • specify a number
  • activate debugging mode
  • show program help

...the find_args could look like this:

ARGS = Console.get_args({
    "files": "before",
    "config": ["-c", "--config"],
    "number": {
        "flags": ["-n", "--numbers"],
        "default": 0,
    },
    "debug": ["-d", "--debug"],
    "help": ["-h", "--help"],
})

The script containing this function could then be executed via the command line like this:

python script.py "/path/to/file1" "/path/to/file2" -c "config.json" --debug

...and therefore the method would return:

Args(
    # FOUND TWO ARGUMENTS BEFORE THE FIRST FLAG
    files=ArgResult(exists=True, value=["/path/to/file1", "/path/to/file2"]),
    # FOUND ONE OF THE SPECIFIED FLAGS WITH A FOLLOWING VALUE
    config=ArgResult(exists=True, value="config.json"),
    # DIDN'T FIND ANY OF THE SPECIFIED FLAGS AND USES DEFAULT VALUE
    number=ArgResult(exists=False, value=0),
    # FOUND ONE OF THE SPECIFIED FLAGS BUT NO FOLLOWING VALUE
    debug=ArgResult(exists=True, value=None),
    # DIDN'T FIND ANY OF THE SPECIFIED FLAGS AND HAS NO DEFAULT VALUE
    help=ArgResult(exists=False, value=None),
)

So if we here would want to check the config arg's value, we can access it like this:

ARGS.config.value

Returned Args Object:

This is the object that stores found command arguments under their aliases with their results. The Args object also has some helpful methods:

  • len(ARGS) returns the number of args (aliases) stored in the object
  • ARGS.dict() returns the stored args as a dictionary
  • ARGS.keys() returns the aliases of the stored args as dict_keys([...])
  • ARGS.values() returns the results of the stored args as dict_values([...])
  • ARGS.items() returns the aliases and results of the stored args as dict_items([...])

pause_exit()

Will print a prompt and then pause and/or exit the program.
Params:

  • prompt: object = "" the prompt to print before pausing and/or exiting the program
  • pause: bool = True whether to pause the program at the message or not
  • exit: bool = False whether to exit the program after the message was printed (and the program was unpaused if pause is true) or not
  • exit_code: int = 0 the exit code to use if exit is true
  • reset_ansi: bool = False whether to reset the ANSI formatting after the prompt was printed

Returns:no return value


cls()

Will clear the console in addition to completely resetting the ANSI formats.
Params:no parameters
Returns:no return value


log()

Will print a nicely formatted log message.
The log message supports special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • title: Optional[str] = None the title of the log message
  • prompt: object = "" the prompt to print before the log message
  • format_linebreaks: bool = True whether to format (indent after) the line breaks or not
  • start: str = "" the string to print before the log message
  • end: str = "\n" the string to print after the log message (default \n)
  • title_bg_color: Optional[Hexa | Rgba] = None the background color of the title
  • default_color: Optional[Hexa | Rgba] = None the default color of the log message
  • tab_size: int = 8 the number of spaces used for the tab, after the title and for formatting line breaks
  • title_px: int = 1 the number of spaces put on the left and right side of the title, inside the title background (horizontal padding)
  • title_mx: int = 2 the number of spaces put on the left and right side of the title, outside the title background (horizontal margin)

Returns:no return value


debug(), info(), done(), warn(), fail(), exit()

These methods are all presets for the Console.log() method, with the options to pause at the message and exit the program after the message was printed. That means, they have the same params as the Console.log() method, with the two additional ones.
Additional Params:

  • active: bool whether to print the prompt or not, to easily enable/disable debug logs (only for the debug() preset)
  • pause: bool whether to pause the program at the prompt or not (different default depending on the log preset)
  • exit: bool whether to exit the program after the prompt was printed (and the program was unpaused if pause is true) or not (different default depending on the log preset)
  • exit_code: int the exit code (0 or 1) to use if exit is true (different default depending on the log preset)
  • reset_ansi: bool whether to reset the ANSI codes after the prompt was printed (different default depending on the log preset)

Returns:no return value


log_box_filled()

Will print a box with a colored background, containing a formatted log message.
The *values can be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • *values: object the box content (each value is on a new line)
  • start: str = "" the string to print before the log box is printed
  • end: str = "\n" the string to print after the log box is printed
  • box_bg_color: str | Rgba | Hexa = "green" the background color of the box
  • default_color: Optional[Rgba | Hexa] = "#000" the default color of the *values
  • w_padding: int = 2 the horizontal padding (in chars) to the box content
  • w_full: bool = False whether to make the box be the full console width or not

Returns:no return value


log_box_bordered()

Will print a bordered box that can be split with horizontal rules and contains a formatted log message.
The *values can be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • *values: object the box content (each value is on a new line)
  • start: str = "" the string to print before
  • end: str = "\n" the string to print after
  • border_type: Literal["standard", "rounded", "strong", "double"] = "rounded" one of the predefined border character sets
  • border_style: str | Rgba | Hexa = f"dim|{COLOR.GRAY}" the style of the border (special formatting codes)
  • default_color: Optional[Rgba | Hexa] = "#000" the default color of the *values
  • w_padding: int = 2 the horizontal padding (in chars) to the box content
  • w_full: bool = False whether to make the box be the full console width or not
  • indent: int = 0 the number of spaces to indent the whole box with
  • _border_chars: Optional[tuple[str, ...]] = None define your own border characters set (overwrites border_type)

Returns:no return value

Horizontal Rules:

If you want to split the box content with horizontal rules, you can do so by putting {hr} inside the *values at the position where you want the horizontal rule to be.

Example:

Console.log_box_bordered(
    "Content",
    "{hr}",
    "More content",
    "Another line",
)

...would output:

┌──────────────┐
│ Content      │
├──────────────┤
│ More content │
│ Another line │
└──────────────┘

Border Types:

The border_type can be one of the following predefined border character sets:
(In an actual console the border-line would be connected with no gaps – here it might not be due to rendering limitations.)

  • standard uses the character set ('┌', '─', '┐', '│', '┘', '─', '└', '│', '├', '─', '┤') which looks like this:
    ┌──────────────┐
    │ Content      │
    ├──────────────┤
    │ More content │
    │ Another line │
    └──────────────┘
  • rounded uses the character set ('╭', '─', '╮', '│', '╯', '─', '╰', '│', '├', '─', '┤') which looks like this:
    ╭──────────────╮
    │ Content      │
    ├──────────────┤
    │ More content │
    │ Another line │
    ╰──────────────╯
  • strong uses the character set ('┏', '━', '┓', '┃', '┛', '━', '┗', '┃', '┣', '━', '┫') which looks like this:
    ┏━━━━━━━━━━━━━━┓
    ┃ Content      ┃
    ┣━━━━━━━━━━━━━━┫
    ┃ More content ┃
    ┃ Another line ┃
    ┗━━━━━━━━━━━━━━┛
  • double uses the character set ('╔', '═', '╗', '║', '╝', '═', '╚', '║', '╠', '═', '╣') which looks like this:
    ╔══════════════╗
    ║ Content      ║
    ╠══════════════╣
    ║ More content ║
    ║ Another line ║
    ╚══════════════╝

Border Chars:

You can also define your own border characters set by passing a tuple of 8 strings to the _border_chars parameter. The characters in the tuple correspond to the following border positions:

  1. top-left corner
  2. top border
  3. top-right corner
  4. right border
  5. bottom-right corner
  6. bottom border
  7. bottom-left corner
  8. left border
  9. left horizontal rule connector
  10. horizontal rule
  11. right horizontal rule connector

Example:

For an even better visual understanding, this is what gets output with the character set ('A', 'b', 'C', 'd', 'E', 'f', 'G', 'h', 'I', 'j', 'K'):

AbbbbbbbbbbbbbbC
h Content      d
IjjjjjjjjjjjjjjK
h More content d
h Another line d
GffffffffffffffE

confirm()

This method can be used to ask a yes/no question.
The prompt can be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • prompt: object the input prompt (question)
  • start: str = "" the string to print before the question-input
  • end: str = "" the string to print after the question-input
  • default_color: Optional[Rgba | Hexa] = None the default color of the question
  • default_is_yes: bool = True whether the default answer is yes or no (if the user continues without entering anything or an unrecognized answer)

Returns:

  • True if the user enters Y or yes and False otherwise
  • If the user entered nothing:
    • True if default_is_yes is true
    • False if default_is_yes is false

multiline_input()

This method allows for user input including linebreaks.
The prompt can be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • prompt: object the input prompt
  • start: str = "" the string to print before the input
  • end: str = "\n" the string to print after the input
  • default_color: Optional[Rgba | Hexa] = None the default color of the input
  • show_keybindings: bool = True whether to display the special keybindings before the input or not
  • input_prefix: str = " ⮡ " the prefix of the first input line
  • reset_ansi: bool = True whether to reset the ANSI codes after the input or not

Returns: the user's entry as a string, with linebreaks as \n


input()

This method acts like a standard Python input() with the advantage, that you can specify:

  • what text characters the user is allowed to type and
  • the minimum and/or maximum length of the user's input
  • optional mask character (hide user input, e.g. for passwords)
  • reset the ANSI formatting codes after the user continues

The prompt can be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • prompt: object the input prompt
  • start: str = "" the string to print before the input
  • end: str = "\n" the string to print after the input
  • default_color: Optional[Rgba | Hexa] = None the default color of the input
  • placeholder: Optional[str] = None a placeholder text that is shown when the input is empty
  • mask_char: Optional[str] = None if set, the input will be masked with this character
  • min_len: Optional[int] = None the minimum length of the input (required to submit)
  • max_len: Optional[int] = None the maximum length of the input (can't write further if reached)
  • allowed_chars: str = CHARS.ALL a string of characters that are allowed to be inputted (default allows all characters)
  • allow_paste: bool = True whether to allow pasting text into the input or not
  • validator: Optional[Callable[[str], Optional[str]]] = None an optional function that takes the current input as a string and returns a string error message if the input is invalid or nothing (None) if the input is valid
  • default_val: Optional[T] = None the default value to return if the input is empty
  • output_type: type[T] = str the type (class) to convert the input to before returning it (will raise an error if conversion fails!)

Returns: the user's entry or the default_val converted to the specified output_type
Raises:ValueErrorTypeError if the input couldn't be converted to the specified output_type

Validator Function:

The validator function is structured the following way:

def my_validator(user_input: str) -> Optional[str]:
    ...

Example:

An E-Mail input with a simple validator function could therefore look like this:

def email_validator(user_input: str) -> Optional[str]:
    if not re.match(r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}", user_input):
        return "Enter a valid E-Mail address (example@domain.com)"

user_input = Console.input(
    prompt="E-Mail: ",
    placeholder="example@domain.com",
    validator=email_validator,
)


ProgressBar

This class can be used to easily display a nice progress bar in the console.

ProgressBar(
    min_width: int = 10,
    max_width: int = 50,
    bar_format: str = "{l} |{b}| [b]({c})/{t} [dim](([i]({p}%)))",
    limited_bar_format: str = "|{b}|",
    chars: tuple[str, ...] = ("█", "▉", "▊", "▋", "▌", "▍", "▎", "▏", " ")
)

The methods of the ProgressBar instance can be used to show, update and hide a progress bar in the console.

There's also an option to use the ProgressBar instance as a context manager, which has a few advantages, such as auto hiding the progress bar when exiting the context.


.set_width()

This method can be used to update the min_width and/or the max_width.
Params:

  • min_width: Optional[int] = None the new minimum width (greater or equal to 1) of the progress bar (or None to not change it)
  • max_width: Optional[int] = None the new maximum width (greater or equal to min_width) of the progress bar (or None to not change it)

Returns:no return value


.set_bar_format()

This method can be used to update the bar_format and/or the limited_bar_format.
The bar_format and limited_bar_format can additionally be formatted with special formatting codes. For more detailed information about formatting codes, see the format_codes documentation.
Params:

  • bar_format: Optional[str] = None the new format of the progress bar (or None to not change it)
  • limited_bar_format: Optional[str] = None the new format of the progress bar, used when the console width is too small for the normal bar_format (or None to not change it)

Returns:no return value

Bar Format Placeholders:

The bar_format and limited_bar_format strings can contain the following placeholders:

  • {bar} {b} the progress bar itself
  • {current} {c} the current progress value
  • {total} {t} the total progress value
  • {percent} {p} the current progress in percent
  • {label} {l} the optional label

.set_chars()

This method can be used to update the chars used to display the progress bar.
Param:chars: tuple[str, ...] a tuple of characters ordered from full to empty progress Returns:no return value

Chars:

The chars tuple must contain at least two characters:

  • the first character represents completely filled sections
  • intermediate characters create smooth transitions
  • the last character represents empty sections

Example:

ProgressBar.set_chars(("█", "▓", "▒", "░", " "))

show_progress()

This method can be used to show or update the progress bar.
Params:

  • current: int the current progress value (below 0 or greater than total hides the bar)
  • total: int the total progress value (must be greater than 0)
  • label: Optional[str] = None an optional label which is inserted at the {label} or {l} placeholder

Returns:no return value


hide_progress()

This method can be used to hide the progress bar.
Params:no parameters
Returns:no return value


progress_context()

This method can be used to use the ProgressBar instance as a context manager.
Params:

  • total: int the total progress value (must be greater than 0)
  • label: Optional[str] = None an optional label which is inserted at the {label} or {l} placeholder

Returns: a context manager which yields a method to update the progress and/or the label

Usage as Context Manager:

The ProgressBar instance can be used as a context manager which yields a method to update the progress and/or the label, within the context.
It will also automatically hide the progress bar when exiting the context, even if an error occurs within the context.

Example:

with ProgressBar().progress_context(500, "Loading...") as update_progress:
    update_progress(0)  # Show empty bar at start

    for i in range(400):
        # Do some work...
        update_progress(i)  # Update progress

    update_progress(label="Finalizing...")  # Update label

    for i in range(400, 500):
        # Do some work...
        update_progress(i, f"Finalizing ({i})")  # Update both

★⠀Python Library by XulbuX⠀★

Project Links

Testing and Formatting

Classifiers

  • Intended Audience:
    • Developers
  • License:
    • OSI Approved
    • MIT License
  • Operating Systems:
    • Full Library: OS Independent
  • Supported Python Versions:
    • Python 3.13
    • Python 3.12
    • Python 3.11
    • Python 3.10
  • Topics:
    • Libraries
    • Python Modules
    • Software Development

The XulbuX Logo
Clone this wiki locally