-
-
Notifications
You must be signed in to change notification settings - Fork 0
console
This class includes methods for logging and other actions within the console.
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
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: dicta dictionary that specifies, which arguments you are looking for and under which alias they should be returned -
allow_spaces: bool = Falsewhether 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:
-
existsisTrueif one of the listed arguments is found andFalseotherwise -
valueis the value of the argument (Noneif the argument has no value)
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 --debugAnd 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.valueThis 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 asdict_keys([...]) -
ARGS.values()returns the results of the stored args asdict_values([...]) -
ARGS.items()returns the aliases and results of the stored args asdict_items([...])
Will print a prompt and then pause and/or exit the program.
Params:
-
pause: bool = Falsewhether to pause the program at the message or not -
exit: bool = Falsewhether to exit the program after the message was printed (and the program was unpaused ifpauseis true) or not -
prompt: str = ""the prompt to print before pausing and/or exiting the program -
exit_code: int = 0the exit code to use ifexitis true -
reset_ansi: bool = Falsewhether to reset the ANSI codes after the message was printed
Returns: no return value
Will clear the console in addition to completely resetting the ANSI formats.
Params: no parameters
Returns: no return value
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: strthe title of the log message -
prompt: object = ""the prompt to print before the log message -
format_linebreaks: bool = Truewhether 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] = Nonethe background color of the title -
default_color: Optional[Hexa | Rgba] = Nonethe default color of the log message -
_console_tabsize: int = 8the 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
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: boolwhether to print the message or not, to easily enable/disable debug logs (not all presets have this parameter) -
pause: boolwhether to pause the program at the message or not (different default depending on the log preset) -
exit: boolwhether to exit the program after the message was printed (and the program was unpaused ifpauseis true) or not (different default depending on the log preset) -
reset_ansi: boolwhether 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
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: objectthe 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 = 2the horizontal padding (in chars) to the box content -
w_full: bool = Falsewhether to make the box be the full console width or not
Returns: no return value
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: objectthe 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 = 2the horizontal padding (in chars) to the box content -
w_full: bool = Falsewhether to make the box be the full console width or not -
_border_chars: Optional[tuple[str,str,str,str,str,str,str,str]] = Nonedefine your own border characters set (overwritesborder_type)
Returns: no return value
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.)
-
standarduses the character set('┌', '─', '┐', '│', '┘', '─', '└', '│')which looks like this:┌──────────────┐ │ Content │ │ More content │ └──────────────┘
-
roundeduses the character set('╭', '─', '╮', '│', '╯', '─', '╰', '│')which looks like this:╭──────────────╮ │ Content │ │ More content │ ╰──────────────╯
-
stronguses the character set('┏', '━', '┓', '┃', '┛', '━', '┗', '┃')which looks like this:┏━━━━━━━━━━━━━━┓ ┃ Content ┃ ┃ More content ┃ ┗━━━━━━━━━━━━━━┛
-
doubleuses the character set('╔', '═', '╗', '║', '╝', '═', '╚', '║')which looks like this:╔══════════════╗ ║ Content ║ ║ More content ║ ╚══════════════╝
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:
- top-left corner
- top border
- top-right corner
- right border
- bottom-right corner
- bottom border
- bottom-left corner
- 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
GffffffffffffffEThis 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: objectthe 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.cyanthe default color of the question -
default_is_yes: bool = Truewhether the default answer is yes or no (if the user continues without entering anything or an unrecognized answer)
Returns:
-
Trueif the user entersYoryesandFalseotherwise - If the user entered nothing:
-
Trueifdefault_is_yesis true -
Falseifdefault_is_yesis false
-
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: objectthe 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.cyanthe default color of the input -
show_keybindings: bool = Truewhether to display the special keybindings before the input or not -
input_prefix: str = " ⮡ "the prefix of the first input line -
reset_ansi: bool = Truewhether to reset the ANSI codes after the input or not
Returns: the user's entry as a string, with linebreaks as \n
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: objectthe 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.cyanthe default color of the input -
allowed_chars: str = CHARS.allthe allowed text characters the user can type (default is all characters) -
min_length: Optional[int] = Nonethe minimum length of the user's input (user can not confirm the input before this length is reached) -
max_length: Optional[int] = Nonethe maximum length of the user's input (user cannot keep on writing if this length is reached) -
mask_char: Optional[str] = Nonethe mask character to hide the user's input -
reset_ansi: bool = Truewhether to reset the ANSI formatting codes after the user continues
Returns: the user's entry as a string
This method works the same as Console.restricted_input(), but it always hides the user's input.
Params:
-
prompt: objectthe 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.cyanthe default color of the input -
allowed_chars: str = CHARS.allthe allowed text characters the user can type (default is all characters) -
min_length: Optional[int] = Nonethe minimum length of the user's input (user can not confirm the input before this length is reached) -
max_length: Optional[int] = Nonethe maximum length of the user's input (user cannot keep on writing if this length is reached) -
reset_ansi: bool = Truewhether to reset the ANSI formatting codes after the user continues
Returns: the user's entry as a string
★⠀Python Library by XulbuX⠀★
-
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