ansi2html
raw JSON → 1.9.2 verified Fri Apr 17 auth: no python
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.
pip install ansi2html Common errors
error NameError: name 'Ansi2HTMLConverter' is not defined ↓
cause The `Ansi2HTMLConverter` class was used without being correctly imported from the `ansi2html` library.
fix
Add the import statement
from ansi2html import Ansi2HTMLConverter at the top of your Python file. error 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.
fix
Use 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`. ↓
fix Always specify `full=False` (e.g., `converter.convert(ansi_text, full=False)`) if you intend to embed the output into another HTML structure. Only use `full=True` if you're generating a standalone HTML file.
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. ↓
fix For `full=False` output, ensure you provide your own CSS to define the `ansi-*` classes. You can copy the default styles from the library's source or create custom ones. For `full=True`, styles are automatically included.
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], "...")