ansi2html
ansi2html is a Python library that converts text containing ANSI escape codes (commonly used for colored terminal output) into HTML or LaTeX markup. It is currently at version 1.9.2 and maintains an active development cycle with regular updates addressing features and minor bug fixes.
Common errors
-
NameError: name 'Ansi2HTMLConverter' is not defined
cause The `Ansi2HTMLConverter` class was used without being correctly imported from the `ansi2html` library.fixAdd the import statement `from ansi2html import Ansi2HTMLConverter` at the top of your Python file. -
AttributeError: module 'ansi2html' has no attribute 'Ansi2HTMLConverter'
cause This usually happens when you try to access the class via `ansi2html.Ansi2HTMLConverter` after doing `import ansi2html`. The class is directly exported, not nested under the module object when using `from ansi2html import ...`. It can also occur if your script file is named `ansi2html.py`, causing a module shadowing issue.fixUse the direct import `from ansi2html import Ansi2HTMLConverter`. If your script file is named `ansi2html.py`, rename it to something else (e.g., `my_script.py`) to avoid conflicting with the library's module name.
Warnings
- gotcha The `convert()` method's `full` parameter defaults to `True`, which generates a complete HTML document including `<html>`, `<head>`, `<body>` tags and embedded CSS. If you only need an HTML fragment to embed within an existing page, you must explicitly set `full=False`.
- gotcha When `full=False` is used, the generated HTML output contains CSS class names (e.g., `ansi-red`, `ansi-bold`) but no inline styles or `<style>` block. If you display this fragment without a corresponding stylesheet, the colors will not render.
Install
-
pip install ansi2html
Imports
- Ansi2HTMLConverter
from ansi2html import Ansi2HTMLConverter
Quickstart
from ansi2html import Ansi2HTMLConverter
import os
# Example ANSI text with colors (red, yellow, green)
ansi_text = "\x1b[31mError:\x1b[0m \x1b[33mWarning:\x1b[0m \x1b[32mSuccess!\x1b[0m"
# Create a converter instance
converter = Ansi2HTMLConverter()
# Convert ANSI text to an HTML fragment (recommended for embedding)
html_fragment = converter.convert(ansi_text, full=False)
print("HTML Fragment:\n", html_fragment)
# To generate a full HTML document with embedded CSS
html_full_doc = converter.convert(ansi_text, full=True, title="ANSI Log Output")
print("\nFull HTML Document (first 200 chars):\n", html_full_doc[:200], "...")