AnsiMarkup
Ansimarkup is a Python library that simplifies producing colored and styled terminal text using an XML-like markup syntax. It translates tags like `<red>Hello</red>` into appropriate ANSI escape codes, supporting various colors, styles (bold, italic, underline), and background colors. The library is currently at version 2.2.0, with stable, albeit infrequent, releases.
Common errors
-
TypeError: 'AnsiMarkup' object is not callable
cause In `ansimarkup` versions 2.0.0 and above, `AnsiMarkup` instances are no longer directly callable like a function. This was a deprecated feature in 1.x and removed in 2.x.fixExplicitly use the `parse` method: `am.parse("<red>Error</red>")` instead of `am("<red>Error</red>")`. -
NameError: name 'strip_markup' is not defined
cause The `strip_markup` function was removed from the top-level `ansimarkup` module and `AnsiMarkup` class in version 2.0.0.fixImport and use the new standalone `strip` function: `from ansimarkup import strip; plain_text = strip("<bold>Markup</bold>")`. -
My terminal output shows raw ANSI escape codes or no colors at all.
cause The terminal you are using may not support ANSI escape codes, or the output is being redirected (e.g., to a file, pipe, or non-interactive environment) where `ansimarkup` might disable colors by default.fixEnsure you are running in an ANSI-compatible terminal (e.g., most Linux/macOS terminals, modern Windows Terminal). If you need to force colors even when output is redirected, you can initialize `AnsiMarkup(force_colors=True)`. However, this might result in raw escape codes in truly incompatible environments or files.
Warnings
- breaking Major API changes in AnsiMarkup 2.0.0 removed direct callability of `AnsiMarkup` instances and arguments like `stdout`/`stream` from the constructor and `parse` method.
- breaking The `strip_markup` function/method was removed from the `AnsiMarkup` class and `ansimarkup` module namespace in version 2.0.0.
- gotcha Tag case-sensitivity changed in AnsiMarkup 2.0.0. Tags are now case-sensitive by default.
Install
-
pip install ansimarkup
Imports
- AnsiMarkup
from ansimarkup import AnsiMarkup
- ansiprint
from ansimarkup import ansiprint
- strip
from ansimarkup import strip_markup
from ansimarkup import strip
Quickstart
from ansimarkup import AnsiMarkup
# Create an AnsiMarkup instance
am = AnsiMarkup()
# Use the parse method to convert markup to ANSI colored text
text = am.parse("<red>Error:</red> <bold>Something went wrong!</bold>")
print(text)
# Or, use ansiprint for direct output
from ansimarkup import ansiprint
ansiprint("<green>Success:</green> Operation complete!")