API Reference¶
Core Classes and Functions¶
ASCIIColors¶
The main class for colored output and logging. Inherits all ANSI color constants.
- class ascii_colors.ASCIIColors[source]¶
Bases:
ANSIDirect printing and logging state manager.
- 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.
Direct color methods:
Logging methods:
Configuration methods:
- classmethod context(**kwargs)[source]¶
- Parameters:
kwargs (Any)
- Return type:
ContextManager[None]
- 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()
Constants¶
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
- 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.
- class ascii_colors.JSONFormatter(fmt=None, datefmt=None, style='%', json_ensure_ascii=False, json_indent=None, json_separators=None, json_sort_keys=False, include_fields=None, include_source=False, **kwargs)[source]¶
Bases:
FormatterFormats log records into JSON strings.
- Parameters:
- __init__(fmt=None, datefmt=None, style='%', json_ensure_ascii=False, json_indent=None, json_separators=None, json_sort_keys=False, include_fields=None, include_source=False, **kwargs)[source]¶
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¶
- class ascii_colors.ProgressBar(iterable=None, total=None, desc='', unit='it', ncols=None, bar_format=None, leave=True, mininterval=0.15, color='\x1b[32m', style='', background='', bar_style='fill', **kwargs)[source]¶
Bases:
objectCustomizable progress bar similar to tqdm.
Questionary Compatibility¶
Drop-in replacement for the questionary library.
- 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.
- ask(patch_stdout=False, kbi_msg='Cancelled by user')[source]¶
Ask the question and return the answer.
- 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.
Validation¶
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 as attributes.
Example usage:
from ascii_colors import questionary name = questionary.text("Your name?").ask() color = questionary.select("Favorite color?", choices=["Red", "Blue"]).ask()
Utility Functions¶
- ascii_colors.get_trace_exception(ex, enhanced=True, max_width=None)[source]¶
Formats an exception and its traceback into a string.
Get a formatted string representation of an exception and its traceback.
- Parameters:
ex (BaseException) – The exception to format
enhanced (bool) – If True, use enhanced formatting with colors and box drawing
max_width (int | None) – Maximum width for output (auto-detected if None)
- Returns:
Formatted traceback string
- Return type:
Internal Classes¶
These classes are primarily for internal use but may be useful for advanced customization.
- class ascii_colors._AsciiLoggerAdapter(name)[source]¶
Bases:
objectAdapter that provides standard logging.Logger interface using ASCIIColors backend.
Adapter class that provides the standard logging.Logger interface while using ascii_colors 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