API Reference¶
Core Classes and Functions¶
ASCIIColors¶
The main class for colored output and logging. Provides both direct printing methods and rich integration convenience functions.
- class ascii_colors.ASCIIColors[source]¶
Bases:
ANSIDirect printing and logging state manager.
- classmethod context(**kwargs)[source]¶
- Parameters:
kwargs (Any)
- Return type:
ContextManager[None]
- static print(text, color='\x1b[37m', style='', background='', end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, emit=True, markup=True)[source]¶
Print text with optional rich markup support.
- Parameters:
text (str) – The text to print
color (str) – Foreground color ANSI code
style (str) – Style ANSI code (bold, italic, etc.)
background (str) – Background color ANSI code
end (str) – String to append at the end
flush (bool) – Whether to flush the output
file (Any) – Output stream
emit (bool) – Whether to actually print (False returns string only)
markup (bool) – Whether to parse rich markup tags like [red], [bold], etc.
- Return type:
- static multicolor(texts, colors, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, emit=True, markup=True)[source]¶
Print multiple colored text segments with rich markup support.
- static highlight(text, subtext, color='\x1b[37m', highlight_color='\x1b[33m', whole_line=False, end='\n', flush=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, markup=False)[source]¶
Highlight substrings in text with optional rich markup support.
- Parameters:
text (str) – The text to process
subtext (str | List[str]) – String or list of strings to highlight
color (str) – Default text color
highlight_color (str) – Color for highlighted portions
whole_line (bool) – Whether to highlight entire lines containing subtext
end (str) – String to append at the end
flush (bool) – Whether to flush the output
file (Any) – Output stream
markup (bool) – Whether to parse rich markup tags in the text first
- Return type:
None
- static confirm(question, default_yes=None, prompt_color='\x1b[33m', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, markup=True)[source]¶
Ask a yes/no confirmation question with optional rich markup support.
- static prompt(text, color='\x1b[32m', style='', hide_input=False, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, markup=True)[source]¶
Prompt for user input with optional rich markup support.
- static rich_print(text, **kwargs)[source]¶
Print text with rich markup support.
Supports tags like [magenta], [bold], [success], [error], etc.
Examples
ASCIIColors.rich_print(“[magenta]Hello[/magenta] [bold]World[/bold]”) ASCIIColors.rich_print(“[success]Operation completed successfully[/success]”) ASCIIColors.rich_print(“[error]An error occurred[/error]”) ASCIIColors.rich_print(“[warning]Warning: deprecated feature[/warning]”) ASCIIColors.rich_print(“[info]Note: processing started[/info]”)
- static panel(content, title=None, border_style='', box='square', padding=(0, 1), width=None, color='', background='')[source]¶
Create a bordered panel around content. Returns string for printing.
New rich-style convenience method.
- static table(*headers, rows=None, title=None, box='square', show_lines=False, header_style='bold')[source]¶
Create a formatted table. Returns string for printing.
New rich-style convenience method.
- static tree(label, style='', guide_style='dim')[source]¶
Create a tree structure for display.
New rich-style convenience method. Returns a Tree object that can have children added.
- static syntax(code, language='python', line_numbers=False, theme=None)[source]¶
Syntax highlight code. Returns string for printing.
New rich-style convenience method.
- static markdown(markup)[source]¶
Render markdown to terminal. Returns string for printing.
New rich-style convenience method.
- static columns(*items, equal=False, width=None)[source]¶
Arrange items in columns. Returns string for printing.
New rich-style convenience method.
- static rule(title='', characters='─', style='', align='center')[source]¶
Print a horizontal rule with optional title.
New rich-style convenience method.
- static status(message, spinner='dots', spinner_style='green')[source]¶
Show a spinner status indicator.
New rich-style convenience method. Use as context manager.
Example
- with ASCIIColors.status(“Processing…”):
do_work()
Direct Printing Methods¶
Color Shortcuts¶
Logging Methods¶
Configuration Methods¶
Rich Integration Convenience Methods¶
Constants¶
- class ascii_colors.LogLevel(value)[source]¶
Bases:
IntEnumEnumeration defining standard logging levels.
- CRITICAL = 50¶
- ERROR = 40¶
- WARNING = 30¶
- INFO = 20¶
- DEBUG = 10¶
- NOTSET = 0¶
Level Constants¶
- ascii_colors.DEBUG = 10¶
- ascii_colors.INFO = 20¶
- ascii_colors.WARNING = 30¶
- ascii_colors.ERROR = 40¶
- ascii_colors.CRITICAL = 50¶
- ascii_colors.NOTSET = 0¶
ANSI Color Constants¶
All available as class attributes on ASCIIColors:
- Styles:
style_bold,style_dim,style_italic,style_underlinestyle_blink,style_reverse,style_hidden,style_strikethrough
- Foreground Colors:
color_black,color_red,color_green,color_yellowcolor_blue,color_magenta,color_cyan,color_white,color_orangeBright variants:
color_bright_*Background colors:
color_bg_*andcolor_bg_bright_*
- Reset:
color_reset
Logging Components¶
Formatters¶
- class ascii_colors.Formatter(fmt=None, datefmt=None, style='%', include_source=False, **kwargs)[source]¶
Bases:
objectBase class for formatting log records into textual representations.
Handlers¶
- class ascii_colors.Handler(level=10, formatter=None)[source]¶
Bases:
ABCAbstract base class for all log handlers.
- class ascii_colors.ConsoleHandler(level=10, formatter=None, stream=None)[source]¶
Bases:
HandlerHandles logging records by writing them to a stream (typically console).
- ascii_colors.StreamHandler¶
alias of
ConsoleHandler
- class ascii_colors.FileHandler(filename, mode='a', encoding='utf-8', delay=False, level=10, formatter=None)[source]¶
Bases:
HandlerHandles logging records by writing them to a file.
- Parameters:
- class ascii_colors.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding='utf-8', delay=False, level=10, formatter=None)[source]¶
Bases:
FileHandlerHandles logging to a file, rotating it when it reaches a certain size.
- Parameters:
- class ascii_colors.handlers[source]¶
Bases:
object- class RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding='utf-8', delay=False, level=10, formatter=None)¶
Bases:
FileHandlerHandles logging to a file, rotating it when it reaches a certain size.
- Parameters:
- do_rollover()¶
- Return type:
None
- class FileHandler(filename, mode='a', encoding='utf-8', delay=False, level=10, formatter=None)¶
Bases:
HandlerHandles logging records by writing them to a file.
- Parameters:
- close()¶
- Return type:
None
- emit(level, formatted_message)¶
- flush()¶
- Return type:
None
- StreamHandler¶
alias of
ConsoleHandler
Standard Library Compatibility¶
- ascii_colors.getLogger(name=None)[source]¶
Get a logger with the specified name.
This function mirrors logging.getLogger() for drop-in compatibility.
- Parameters:
name (str | None)
- Return type:
- ascii_colors.basicConfig(*, filename=None, filemode='a', format=None, datefmt=None, style='%', level=None, stream=None, handlers=None, force=False)[source]¶
Configure basic logging.
Mirrors logging.basicConfig() for drop-in compatibility.
- ascii_colors.trace_exception(ex, enhanced=False, max_width=None)[source]¶
Logs the traceback of a given exception.
- Parameters:
ex (BaseException)
enhanced (bool)
max_width (int)
- Return type:
None
- ascii_colors.get_trace_exception(ex, enhanced=True, max_width=None)[source]¶
Formats an exception and its traceback into a string.
- Parameters:
ex (BaseException)
enhanced (bool)
max_width (int | None)
- Return type:
Interactive Components¶
ProgressBar¶
Rich Integration Module¶
The ascii_colors.rich module provides Rich-compatible components.
Rich Module Instance¶
- ascii_colors.rich: RichModule¶
Module-like object providing Rich-compatible functionality.
Example:
from ascii_colors import rich rich.print("[bold red]Hello[/bold red]") rich.rule("Section")
Console¶
- class ascii_colors.rich.Console(width=None, height=None, file=None, force_terminal=None, force_jupyter=None, force_width=None, force_height=None, no_color=False, tab_size=4, record=False, markup=True, emoji=True, emoji_variant=None, highlight=True, log_time=True, log_path=True, log_time_format='[%X]', highlighter=None, legacy_windows=None, safe_box=True, get_environ=<function Console.<lambda>>, get_time=None, get_terminal_size=None)[source]¶
Bases:
objectConsole for rich text output.
- Parameters:
width (int | None)
height (int | None)
file (TextIO | None)
force_terminal (bool | None)
force_jupyter (bool | None)
force_width (int | None)
force_height (int | None)
no_color (bool)
tab_size (int)
record (bool)
markup (bool)
emoji (bool)
emoji_variant (str | None)
highlight (bool)
log_time (bool)
log_path (bool)
log_time_format (str)
highlighter (Any | None)
legacy_windows (bool | None)
safe_box (bool)
- render(renderable, options=None)[source]¶
Render a renderable to lines.
- Parameters:
renderable (Renderable | str)
options (ConsoleOptions | None)
- Return type:
- print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, crop=True, soft_wrap=False, flush=False)[source]¶
Print objects to the console.
- log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None)[source]¶
Log to console with timestamp.
Style and Color¶
- class ascii_colors.rich.Style(color=None, background=None, bold=None, dim=None, italic=None, underline=None, blink=None, reverse=None, strike=None)[source]¶
Bases:
objectRepresents text styling (color, bold, italic, etc.).
- Parameters:
- class ascii_colors.rich.Color(name=None, rgb=None)[source]¶
Bases:
objectRepresents a color for terminal output.
Text and Renderables¶
- class ascii_colors.rich.Text(text=None, style=None, justify=None, overflow='fold', no_wrap=False, end='')[source]¶
Bases:
RenderableA renderable text object with styling.
- Parameters:
Layout Components¶
- class ascii_colors.rich.Panel(renderable, title=None, title_align='center', style=None, border_style=None, box=BoxStyle.SQUARE, padding=(0, 1), width=None, height=None, expand=True)[source]¶
Bases:
objectA bordered panel around content.
This class properly handles: - Emoji and wide characters (counted as 2 terminal columns) - Rich markup tags like [bold], [red], etc. - ANSI escape codes for colors and styles - Multi-line content with proper wrapping
- Parameters:
Data Display¶
- class ascii_colors.rich.Table(*headers, title=None, caption=None, width=None, min_width=None, box=BoxStyle.SQUARE, padding=(0, 1), collapse_padding=False, pad_edge=True, expand=False, show_header=True, show_edge=True, show_lines=False, safe_box=None, padding_style=None, header_style=None, row_styles=None, border_style=None)[source]¶
Bases:
RenderableA table with rows and columns.
- Parameters:
- class ascii_colors.rich.Tree(label, *, style=None, guide_style=None, expanded=True, highlight=False)[source]¶
Bases:
RenderableA tree structure for display.
- Parameters:
Content Components¶
- class ascii_colors.rich.Syntax(code, lexer='python', line_numbers=False, line_number_start=1, highlight_lines=None, code_width=None, tab_size=4, theme=None, word_wrap=False, indent_guides=False, padding=0)[source]¶
Bases:
RenderableSyntax highlighted code.
Live Display¶
- class ascii_colors.rich.Live(renderable=None, console=None, screen=False, auto_refresh=True, refresh_per_second=4, vertical_overflow='ellipsis', get_renderable=None)[source]¶
Bases:
objectLive updating display.
- Parameters:
renderable (Renderable | None)
console (Console | None)
screen (bool)
auto_refresh (bool)
refresh_per_second (float)
vertical_overflow (str)
get_renderable (Callable[[], Renderable] | None)
- update(renderable, *, refresh=False)[source]¶
Update the renderable.
- Parameters:
renderable (Renderable)
refresh (bool)
- Return type:
None
Questionary Compatibility¶
Drop-in replacement for the questionary library.
Base Classes¶
- class ascii_colors.questionary.Question(message, default=None, validate=None, style=None, **kwargs)[source]¶
Bases:
objectBase class for all question types.
- Parameters:
- ask(patch_stdout=False, kbi_msg='Cancelled by user')[source]¶
Ask the question and return the answer.
Question Types¶
- ascii_colors.questionary.Text¶
alias of
PromptText
- class ascii_colors.questionary.Password(message, default='', validate=None, style=None, **kwargs)[source]¶
Bases:
PromptTextPassword input (hidden).
- class ascii_colors.questionary.Confirm(message, default=True, style=None, **kwargs)[source]¶
Bases:
QuestionYes/No confirmation question.
- class ascii_colors.questionary.Select(message, choices, default=None, style=None, **kwargs)[source]¶
Bases:
QuestionSingle selection from list.
- class ascii_colors.questionary.Checkbox(message, choices, default=None, style=None, **kwargs)[source]¶
Bases:
QuestionMultiple selection from list.
- Parameters:
- ask(patch_stdout=False, kbi_msg='Cancelled by user')[source]¶
Ask the question and return the answer.
- class ascii_colors.questionary.Autocomplete(message, choices, default='', validate=None, style=None, **kwargs)[source]¶
Bases:
PromptTextText input with autocomplete suggestions.
Convenience Functions¶
- ascii_colors.questionary.text(message, default='', validate=None, style=None, **kwargs)[source]¶
Create a text input question.
- ascii_colors.questionary.password(message, default='', validate=None, style=None, **kwargs)[source]¶
Create a password input question.
- ascii_colors.questionary.confirm(message, default=True, style=None, **kwargs)[source]¶
Create a yes/no confirmation question.
- ascii_colors.questionary.select(message, choices, default=None, style=None, **kwargs)[source]¶
Create a single-select question.
- ascii_colors.questionary.checkbox(message, choices, default=None, style=None, **kwargs)[source]¶
Create a multi-select checkbox question.
- ascii_colors.questionary.autocomplete(message, choices, default='', validate=None, style=None, **kwargs)[source]¶
Create an autocomplete text input question.
Module-Level Access¶
For drop-in replacement of questionary:
- ascii_colors.questionary: _QuestionaryModule¶
Module-like object with all questionary functions and classes.
Example:
from ascii_colors import questionary name = questionary.text("Your name?").ask()
Utility Functions¶
- ascii_colors.get_trace_exception(ex, enhanced=True, max_width=None)[source]¶
Formats an exception and its traceback into a string.
- Parameters:
ex (BaseException)
enhanced (bool)
max_width (int | None)
- Return type:
Internal Classes¶
- class ascii_colors._AsciiLoggerAdapter(name)[source]¶
Bases:
objectAdapter that provides standard logging.Logger interface using ASCIIColors backend.
- Parameters:
name (str)
- isEnabledFor(level)[source]¶
Check if this logger is enabled for the specified level.
This is a standard logging.Logger method that checks whether a message at the given level would actually be logged.
- warning(msg, *args, **kwargs)[source]¶
Log a warning message.
- Parameters:
msg (str)
- Return type:
None
- warn(msg, *args, **kwargs)[source]¶
Deprecated alias for warning.
- Parameters:
msg (str)
- Return type:
None
- critical(msg, *args, **kwargs)[source]¶
Log a critical message.
- Parameters:
msg (str)
- Return type:
None
- fatal(msg, *args, **kwargs)[source]¶
Log a fatal message (alias for critical).
- Parameters:
msg (str)
- Return type:
None
- exception(msg, *args, **kwargs)[source]¶
Log an exception message with traceback.
- Parameters:
msg (str)
- Return type:
None
- addHandler(hdlr)[source]¶
Add a handler to this logger.
- Parameters:
hdlr (Handler)
- Return type:
None
- removeHandler(hdlr)[source]¶
Remove a handler from this logger.
- Parameters:
hdlr (Handler)
- Return type:
None
- class ascii_colors._QuestionaryModule[source]¶
Bases:
objectModule-like object for drop-in questionary compatibility.
- class ascii_colors.rich.RichModule[source]¶
Bases:
objectModule-like interface for rich compatibility.
- print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None)[source]¶
Print to the default console.
- rule(title='', characters='─', style=None, align='center')[source]¶
Print a rule to the default console.
- prompt(prompt='', *, markup=True, emoji=True, password=False)[source]¶
Get input from the user with a rich prompt.
- class Console(width=None, height=None, file=None, force_terminal=None, force_jupyter=None, force_width=None, force_height=None, no_color=False, tab_size=4, record=False, markup=True, emoji=True, emoji_variant=None, highlight=True, log_time=True, log_path=True, log_time_format='[%X]', highlighter=None, legacy_windows=None, safe_box=True, get_environ=<function Console.<lambda>>, get_time=None, get_terminal_size=None)¶
Bases:
objectConsole for rich text output.
- Parameters:
width (int | None)
height (int | None)
file (TextIO | None)
force_terminal (bool | None)
force_jupyter (bool | None)
force_width (int | None)
force_height (int | None)
no_color (bool)
tab_size (int)
record (bool)
markup (bool)
emoji (bool)
emoji_variant (str | None)
highlight (bool)
log_time (bool)
log_path (bool)
log_time_format (str)
highlighter (Any | None)
legacy_windows (bool | None)
safe_box (bool)
- capture()¶
Capture console output.
- clear(home=False)¶
Clear the console.
- input(prompt='', *, markup=True, emoji=True, password=False, stream=None)¶
Get input from user with styled prompt.
- log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None)¶
Log to console with timestamp.
- print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None, markup=None, highlight=None, width=None, crop=True, soft_wrap=False, flush=False)¶
Print objects to the console.
- render(renderable, options=None)¶
Render a renderable to lines.
- Parameters:
renderable (Renderable | str)
options (ConsoleOptions | None)
- Return type:
- restore_screen()¶
Restore saved screen.
- rule(title='', characters='─', style=None, align='center')¶
Print a horizontal rule.
- save_screen()¶
Save current screen.
- class Text(text=None, style=None, justify=None, overflow='fold', no_wrap=False, end='')¶
Bases:
RenderableA renderable text object with styling.
- Parameters:
- append(text, style=None)¶
Append text to this Text object.
- pad(width, align='left', char=' ')¶
Pad text to width with alignment.
- truncate(max_width, overflow=None)¶
Truncate text to max_width.
- class Style(color=None, background=None, bold=None, dim=None, italic=None, underline=None, blink=None, reverse=None, strike=None)¶
Bases:
objectRepresents text styling (color, bold, italic, etc.).
- Parameters:
- class Panel(renderable, title=None, title_align='center', style=None, border_style=None, box=BoxStyle.SQUARE, padding=(0, 1), width=None, height=None, expand=True)¶
Bases:
objectA bordered panel around content.
This class properly handles: - Emoji and wide characters (counted as 2 terminal columns) - Rich markup tags like [bold], [red], etc. - ANSI escape codes for colors and styles - Multi-line content with proper wrapping
- Parameters:
- classmethod fit(renderable, title=None, title_align='center', style=None, border_style=None, box=BoxStyle.SQUARE, padding=(0, 1), width=None, height=None)¶
Create a panel that is just wide enough to fit its content.
- class Columns(renderables, padding=1, width=None, equal=False, column_first=False)¶
Bases:
objectArrange renderables in columns.
- class Table(*headers, title=None, caption=None, width=None, min_width=None, box=BoxStyle.SQUARE, padding=(0, 1), collapse_padding=False, pad_edge=True, expand=False, show_header=True, show_edge=True, show_lines=False, safe_box=None, padding_style=None, header_style=None, row_styles=None, border_style=None)¶
Bases:
RenderableA table with rows and columns.
- Parameters:
- add_column(header='', style=None, no_wrap=False, width=None, justify='left')¶
Add a column to the table.
- class Tree(label, *, style=None, guide_style=None, expanded=True, highlight=False)¶
Bases:
RenderableA tree structure for display.
- Parameters:
- add(label, *, style=None)¶
Add a child node.
- class Syntax(code, lexer='python', line_numbers=False, line_number_start=1, highlight_lines=None, code_width=None, tab_size=4, theme=None, word_wrap=False, indent_guides=False, padding=0)¶
Bases:
RenderableSyntax highlighted code.
- class Markdown(markup, code_theme=None, justify=None, style=None, hyperlinks=True)¶
Bases:
RenderableMarkdown rendering for terminal.
- class Live(renderable=None, console=None, screen=False, auto_refresh=True, refresh_per_second=4, vertical_overflow='ellipsis', get_renderable=None)¶
Bases:
objectLive updating display.
- Parameters:
renderable (Renderable | None)
console (Console | None)
screen (bool)
auto_refresh (bool)
refresh_per_second (float)
vertical_overflow (str)
get_renderable (Callable[[], Renderable] | None)
- refresh()¶
Force a refresh.
- Return type:
None
- start()¶
Start the live display.
- Return type:
None
- stop()¶
Stop the live display.
- Return type:
None
- update(renderable, *, refresh=False)¶
Update the renderable.
- Parameters:
renderable (Renderable)
refresh (bool)
- Return type:
None
- class Status(status, *, console=None, spinner='dots', spinner_style=None, speed=1.0)¶
Bases:
objectStatus spinner display.
- Parameters:
- SPINNERS = {'arrow': '←↖↑↗→↘↓↙', 'dots': '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', 'line': '⎺⎻⎼⎽⎼⎻', 'moon': '🌑🌒🌓🌔🌕🌖🌗🌘', 'pulse': '◐◓◑◒', 'star': '✶✸✹✺✹✷'}¶
- start()¶
Start the status display.
- Return type:
None
- stop()¶
Stop the status display.
- Return type:
None
- class BoxStyle(value)¶
Bases:
EnumBox drawing styles.
- SQUARE = 'square'¶
- ROUND = 'round'¶
- MINIMAL = 'minimal'¶
- MINIMAL_HEAVY_HEAD = 'minimal_heavy_head'¶
- SIMPLE = 'simple'¶
- SIMPLE_HEAD = 'simple_head'¶
- DOUBLE = 'double'¶
- class ConsoleOptions(max_width=80, min_width=1, max_height=None, legacy_windows=None, ascii_only=False, size=None)¶
Bases:
objectOptions for rendering to console.
- Parameters:
- class Measurement(minimum, maximum)¶
Bases:
objectMeasurement of renderable dimensions.
- classmethod get(console, options, renderable)¶
Get measurement of a renderable.
- Parameters:
console (Console)
options (ConsoleOptions)
renderable (Renderable)
- Return type:
- normalize()¶
Ensure minimum <= maximum.
- Return type:
- class Rule(title='', characters='─', style=None, align='center')¶
Bases:
RenderableA horizontal rule with optional title.