Pygments ANSI Color
Pygments ANSI Color (version 0.3.0) provides a Pygments lexer specifically designed to highlight ANSI escape codes for colors and styles. It allows Pygments to correctly render colored terminal output, making it readable and formatted. The library has a slow release cadence, with the last update in September 2022, but remains functional for its intended purpose.
Common errors
-
ModuleNotFoundError: No module named 'pygments_ansi_color'
cause The 'pygments-ansi-color' library is not installed in the current Python environment.fixRun `pip install pygments-ansi-color` to install the library. -
NameError: name 'AnsiColorLexer' is not defined
cause The `AnsiColorLexer` class was used in the code without being imported first.fixAdd `from pygments_ansi_color import AnsiColorLexer` at the top of your Python script. -
Output shows raw ANSI escape codes instead of colored text.
cause The Pygments formatter being used does not render ANSI escape codes for the specific output environment, or the terminal itself doesn't support them.fixEnsure you are using a Pygments formatter like `TerminalFormatter` for terminal output and that your terminal emulator is configured to display ANSI colors. Example: `highlight(code, AnsiColorLexer(), TerminalFormatter())`.
Warnings
- gotcha This library provides a Pygments *lexer*, not a standalone formatter. You still need a Pygments formatter (e.g., `TerminalFormatter` or `HtmlFormatter`) to render the highlighted output.
- gotcha The `Pygments` library itself is a required dependency for `pygments-ansi-color` to function, but it may not be automatically installed. You might need to install `Pygments` separately.
- gotcha The lexer primarily focuses on ANSI color and style codes. It may not fully parse or render all complex ANSI escape sequences (e.g., cursor manipulation, advanced screen control codes) that are not directly related to text styling.
Install
-
pip install pygments-ansi-color
Imports
- AnsiColorLexer
from pygments_ansi_color import AnsiColorLexer
Quickstart
from pygments import highlight from pygments.formatters import TerminalFormatter from pygments_ansi_color import AnsiColorLexer # Example string with ANSI color codes ansi_string = "\u001b[31mError: Something went wrong!\u001b[0m \u001b[32mSuccess: Operation completed.\u001b[0m" # Highlight the string using AnsiColorLexer and output to terminal highlighted_output = highlight(ansi_string, AnsiColorLexer(), TerminalFormatter()) print(highlighted_output)