Skip to content

console

XulbuX edited this page Aug 25, 2025 · 13 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, which arguments you are looking for 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 (None if the argument has no value)

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 two options:

  • 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 a filepath, a list of numbers, activate debugging mode and get help, the find_args could look like this:

ARGS = Console.get_args({
    "filepath": ["-f", "--file", "-p", "--path"],
    "numbers": {
        "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 -f /path/to/file --debug

And therefore the method would return:

Args(
    # FOUND ONE OF THE SPECIFIED FLAGS WITH A FOLLOWING VALUE
    filepath=ArgResult(exists=True, value="/path/to/file"),
    # DIDN'T FIND ANY OF THE SPECIFIED FLAGS AND USES DEFAULT VALUE
    numbers=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 filepath args value, we can access it like this:

ARGS.filepath.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 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:

  • pause: bool = False 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
  • prompt: str = "" the prompt to print before pausing and/or exiting the program
  • exit_code: int = 0 the exit code to use if exit is true
  • reset_ansi: bool = False whether to reset the ANSI codes after the message 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: str 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
  • _console_tabsize: int = 8 the tab size of the console (should not have to be changed, since per default the console uses 8 spaces for tabs)

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 message or not, to easily enable/disable debug logs (not all presets have this parameter)
  • pause: bool whether to pause the program at the message or not (different default depending on the log preset)
  • exit: bool whether to exit the program after the message was printed (and the program was unpaused if pause is true) or not (different default depending on the log preset)
  • reset_ansi: bool whether to reset the ANSI codes after the message was printed (not all presets have this parameter | 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, 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
  • 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
  • _border_chars: Optional[tuple[str,str,str,str,str,str,str,str]] = None define your own border characters set (overwrites border_type)

Returns:no return value

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.)

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

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

Example:

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

AbbbbbbbbbbbbbbC
h Content      d
h More content 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 prompt to print before the question
  • start: str = "" the string to print before the question
  • end: str = "\n" the string to print after the question
  • default_color: Optional[Rgba | Hexa] = COLOR.cyan 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 prompt to print before the input
  • start: str = "" the string to print before the input
  • end: str = "\n" the string to print after the input
  • default_color: Optional[Rgba | Hexa] = COLOR.cyan 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


restricted_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 prompt to print before the input
  • start: str = "" the string to print before the input
  • end: str = "\n" the string to print after the input
  • default_color: Optional[Rgba | Hexa] = COLOR.cyan the default color of the input
  • allowed_chars: str = CHARS.all the allowed text characters the user can type (default is all characters)
  • min_length: Optional[int] = None the minimum length of the user's input (user can not confirm the input before this length is reached)
  • max_length: Optional[int] = None the maximum length of the user's input (user cannot keep on writing if this length is reached)
  • mask_char: Optional[str] = None the mask character to hide the user's input
  • reset_ansi: bool = True whether to reset the ANSI formatting codes after the user continues

Returns: the user's entry as a string


pwd_input()

This method works the same as Console.restricted_input(), but it always hides the user's input.
Params:

  • prompt: object the prompt to print before the input
  • start: str = "" the string to print before the input
  • end: str = "\n" the string to print after the input
  • default_color: Optional[Rgba | Hexa] = COLOR.cyan the default color of the input
  • allowed_chars: str = CHARS.all the allowed text characters the user can type (default is all characters)
  • min_length: Optional[int] = None the minimum length of the user's input (user can not confirm the input before this length is reached)
  • max_length: Optional[int] = None the maximum length of the user's input (user cannot keep on writing if this length is reached)
  • reset_ansi: bool = True whether to reset the ANSI formatting codes after the user continues

Returns: the user's entry as a string

★⠀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