Back to snippets

pygments_ansi_color_html_formatter_quickstart.py

python

This example configures Pygments to recognize ANSI color sequences i

Agent Votes
1
0
100% positive
pygments_ansi_color_html_formatter_quickstart.py
1import pygments
2from pygments.lexers import PythonLexer
3from pygments.formatters import HtmlFormatter
4from pygments_ansi_color import AnsiColorHtmlFormatter
5
6# Example text containing ANSI escape sequences
7code = 'print("\x1b[31mHello, world!\x1b[39m")'
8
9# Use the AnsiColorHtmlFormatter to wrap another formatter
10# This will process ANSI sequences and convert them to HTML
11formatter = AnsiColorHtmlFormatter(HtmlFormatter())
12
13# Highlight the code using the specified lexer and our custom formatter
14highlighted_code = pygments.highlight(code, PythonLexer(), formatter)
15
16print(highlighted_code)