string#
color#
from toolbox.string import color
- class Format[source]#
Creates a new ANSI format that can be called to retrieve a styled string.
- Parameters:
code (
int
) – ANSI code.
Example:
from toolbox.string.color import Format bold = Format(code="1") print(bold("hello world"))
Out-of-the-box this module includes the following
toolbox.string.color.Format
definitions:Foreground Color
Background Color
Styles
black
bblack
reset
red
bred
bold
green
bgreen
underline
yellow
byellow
blink
blue
bblue
reverse
magenta
bmagenta
conceal
cyan
bcyan
white
bwhite
These can be utilized like so:
from toolbox.string.color import bold print(bold("Hello world!"))
- class Style[source]#
Initializes a complex ANSI style that can be called to retrieve a styled string.
- Parameters:
args (
Tuple
[Union
[str
,int
,Format
]]) – Arguments that can be either a string, integer, or Format type to create a new ANSI style.reset (
bool
) – Boolean flag that when set to True will append the ANSI reset code to ensure no style spill over.
Note
Style
can take arguments of type string, int, and Format. When using string, it will look up the ANSI code in the 16-bit ANSI dictionary. To use a non-standard code use either a custom Format, or an integer representation of the ANSI code.Example:
from toolbox.string.color import Style, red # ANSI code 1 is bold. error = Style(red, 1, "underline") print(error("This is an error"))
- supports_color()[source]#
Checks if system’s terminal has color support.
Note
This piece of code is from Django’s source code here.
Copyright (c) Django Software Foundation and individual contributors.
- Return type:
bool
- strip_ansi(text)[source]#
Removes ANSI color/style sequence.
- Parameters:
text (
str
) – String to remove ANSI style from.
Example
from toolbox import strip_ansi, red print(strip_ansi(red("hello world")))
- Return type:
str
Module Data#
ANSI
#
Dictionary with 16-bit ANSI codes.
ANSI = {
# Foreground Colors
"black": "30",
"red": "31",
"green": "32",
"yellow": "33",
"blue": "34",
"magenta": "35",
"cyan": "36",
"white": "37",
# Background Colors
"bblack": "40",
"bred": "41",
"bgreen": "42",
"byellow": "43",
"bblue": "44",
"bmagenta": "45",
"bcyan": "46",
"bwhite": "47",
# Styles
"reset": "0",
"bold": "1",
"underline": "4",
"blink": "5",
"reverse": "7",
"conceal": "8",
}
EC
#
ANSI escape character that toolbox.color uses.
EC = "\x1B"
To modify the escape character, one may do the following:
from toolbox.string.color import red
import toolbox
toolbox.string.color.EC = "\t"
print(red("hello world").encode("utf-8"))
# b'\t[31mhello world\t[0m'