Skip to content

Examples

Five small programs, each one job you are likely to need. They live in the repository's examples/ folder and run as they are:

uv run python examples/logging_handler.py

Every screenshot on this page comes from running the example itself (see tools/make_examples.py), and the code shown is the file, included verbatim.

Python logging, colored by level

Route the standard logging module into the viewer. The handler colors the level name and hands each line to the GUI thread through a queued signal, so records logged from worker threads are safe too.

Seven log records in the viewer with colored INFO, DEBUG, WARNING, ERROR and bold CRITICAL level names, the last one logged from a worker thread Seven log records in the viewer with colored INFO, DEBUG, WARNING, ERROR and bold CRITICAL level names, the last one logged from a worker thread

Sample records, the last one from a background thread.
examples/logging_handler.py
examples/logging_handler.py
"""Route Python ``logging`` into an AnsiTextViewer, colored by level.

Run with ``uv run python examples/logging_handler.py``. Records logged from
any thread land in the viewer, because the handler hands each line to the
GUI thread through a queued Qt signal.
"""

import logging
import random
import sys
import threading

from PySide6.QtCore import QObject, QTimer, Signal
from PySide6.QtWidgets import QApplication

from ansi_text_viewer import AnsiTextViewer

LEVEL_COLORS = {
    logging.DEBUG: "36",  # cyan
    logging.INFO: "32",  # green
    logging.WARNING: "33",  # yellow
    logging.ERROR: "31",  # red
    logging.CRITICAL: "1;31",  # bold red
}


class AnsiFormatter(logging.Formatter):
    """Format records normally, then color the level name."""

    def format(self, record: logging.LogRecord) -> str:
        """Return the formatted record with its level name in ANSI color."""
        text = super().format(record)
        color = LEVEL_COLORS.get(record.levelno, "0")
        colored = f"\x1b[{color}m{record.levelname}\x1b[0m"
        return text.replace(record.levelname, colored, 1)


class _Bridge(QObject):
    line = Signal(str)


class ViewerHandler(logging.Handler):
    """A logging handler that appends to a viewer, safe from any thread."""

    def __init__(self, viewer: AnsiTextViewer):
        """Connect to *viewer*; the connection is queued across threads."""
        super().__init__()
        self._bridge = _Bridge()
        self._bridge.line.connect(viewer.appendAnsiText)

    def emit(self, record: logging.LogRecord) -> None:
        """Send one formatted record to the viewer."""
        try:
            self._bridge.line.emit(self.format(record) + "\n")
        except Exception:
            self.handleError(record)


def build() -> tuple[AnsiTextViewer, logging.Logger]:
    """Create the viewer and a logger that writes into it."""
    viewer = AnsiTextViewer()
    viewer.setWindowTitle("logging -> AnsiTextViewer")
    handler = ViewerHandler(viewer)
    handler.setFormatter(
        AnsiFormatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s", "%H:%M:%S")
    )
    logger = logging.getLogger("app")
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    return viewer, logger


SAMPLES = [
    (logging.INFO, "server listening on :8080"),
    (logging.DEBUG, "cache warmed with 412 entries"),
    (logging.WARNING, "slow query took 1.8s"),
    (logging.ERROR, "upstream returned 502"),
    (logging.INFO, "request served in 41ms"),
    (logging.CRITICAL, "disk almost full (98%)"),
]


def worker(logger: logging.Logger, stop: threading.Event) -> None:
    """Log from a background thread to show the handler is thread-safe."""
    log = logger.getChild("worker")
    while not stop.wait(1.3):
        log.info("background job tick")


def main() -> None:
    """Show the viewer and keep logging sample records."""
    app = QApplication(sys.argv)
    viewer, logger = build()
    viewer.resize(820, 420)
    viewer.show()

    timer = QTimer(interval=700)
    timer.timeout.connect(lambda: logger.log(*random.choice(SAMPLES)))
    timer.start()

    stop = threading.Event()
    threading.Thread(target=worker, args=(logger, stop), daemon=True).start()
    app.aboutToQuit.connect(stop.set)
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

Run a command

A command box with Run and Stop. Output streams in as the process writes it, \r progress lines overwrite in place, the view clears on each run, and the exit code is reported in green or red. Leave the box empty to run a built-in demo build.

The command runner after the demo build: a progress line at 100%, ok, warn and fail lines in color, a clickable utils.py:3 link, and a red exit 1 The command runner after the demo build: a progress line at 100%, ok, warn and fail lines in color, a clickable utils.py:3 link, and a red exit 1

The demo build run to completion; utils.py:3 is a clickable file link.
examples/run_command.py
examples/run_command.py
"""A small command runner: type a command, press Run, watch it stream.

Run with ``uv run python examples/run_command.py``. Output is decoded
incrementally, the view clears on every new run, and the exit code is
reported in color when the process ends.
"""

import codecs
import shlex
import sys

from PySide6.QtCore import QProcess
from PySide6.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QLineEdit,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

from ansi_text_viewer import AnsiTextViewer

# A self-contained default so the example works anywhere Python runs.
DEMO = r"""
import time
for step in range(0, 101, 25):
    print(f"\rbuilding... {step}%", end="", flush=True)
    time.sleep(0.15)
print()
print("\x1b[32mok\x1b[0m   compiled 12 modules")
print("\x1b[33mwarn\x1b[0m unused import in utils.py:3")
print("\x1b[31mfail\x1b[0m test_session.py::test_load")
raise SystemExit(1)
"""


class CommandRunner(QWidget):
    """A command line, Run/Stop buttons, and a viewer for the output."""

    def __init__(self):
        """Build the window and wire the process signals."""
        super().__init__()
        self.setWindowTitle("Run a command")
        self.command = QLineEdit(placeholderText="Command to run (empty: demo build)")
        self.run_button = QPushButton("Run")
        self.stop_button = QPushButton("Stop", enabled=False)
        self.viewer = AnsiTextViewer()
        self.viewer.setClearOnStart(True)

        bar = QHBoxLayout()
        bar.addWidget(self.command)
        bar.addWidget(self.run_button)
        bar.addWidget(self.stop_button)
        layout = QVBoxLayout(self)
        layout.addLayout(bar)
        layout.addWidget(self.viewer)

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)
        self.process.readyReadStandardOutput.connect(self.read_output)
        self.process.finished.connect(self.finished)
        self.run_button.clicked.connect(self.run)
        self.stop_button.clicked.connect(self.process.kill)

    def run(self) -> None:
        """Start the typed command, or the demo build when the box is empty."""
        text = self.command.text().strip()
        args = shlex.split(text) if text else [sys.executable, "-c", DEMO]
        self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
        self.viewer.beginNewStream()
        self.viewer.appendAnsiText(f"\x1b[90m$ {text or 'demo build'}\x1b[0m\n")
        self.process.start(args[0], args[1:])
        self.run_button.setEnabled(False)
        self.stop_button.setEnabled(True)

    def read_output(self) -> None:
        """Append whatever the process has written so far."""
        data = self.process.readAllStandardOutput().data()
        self.viewer.appendAnsiText(self.decoder.decode(data))

    def finished(self, code: int, status: QProcess.ExitStatus) -> None:
        """Report the exit code and re-enable Run."""
        self.viewer.appendAnsiText(self.decoder.decode(b"", final=True))
        color = "32" if code == 0 else "31"
        self.viewer.appendAnsiText(f"\x1b[{color}m[exit {code}]\x1b[0m\n")
        self.run_button.setEnabled(True)
        self.stop_button.setEnabled(False)


def build() -> CommandRunner:
    """Create the runner window."""
    return CommandRunner()


def main() -> None:
    """Show the runner."""
    app = QApplication(sys.argv)
    runner = build()
    runner.resize(820, 420)
    runner.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

Follow a log file

tail -f for any file: pass a path, or run it without one to follow a demo log. The file is polled, which works on every platform and for files any program writes; when the file shrinks (rotation, truncation) the view says so and starts again from the top.

Six colored lines followed from app.log, with a yellow notice where the file was truncated Six colored lines followed from app.log, with a yellow notice where the file was truncated

Four lines appended, then the file truncated and written again.
examples/tail_file.py
examples/tail_file.py
"""Follow a growing log file, like ``tail -f``.

Run with ``uv run python examples/tail_file.py path/to/app.log``. Without a
path, it writes a demo log to a temporary file and follows that. The file is
polled, which works on every platform and for files written by any program;
if the file shrinks (log rotation, truncation) it starts again from the top.
"""

import codecs
import sys
import tempfile
from pathlib import Path

from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication

from ansi_text_viewer import AnsiTextViewer


class FileTail:
    """Poll *path* and append new bytes to *viewer*."""

    def __init__(self, viewer: AnsiTextViewer, path: Path, interval_ms: int = 250):
        """Start following *path* from its beginning."""
        self.viewer = viewer
        self.path = path
        self.offset = 0
        self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
        self.timer = QTimer(interval=interval_ms)
        self.timer.timeout.connect(self.poll)
        self.timer.start()
        self.poll()

    def poll(self) -> None:
        """Read anything appended since the last poll."""
        try:
            size = self.path.stat().st_size
        except FileNotFoundError:
            return
        if size < self.offset:  # rotated or truncated
            self.offset = 0
            self.decoder.reset()
            self.viewer.appendAnsiText(
                f"\x1b[33m--- {self.path.name} truncated ---\x1b[0m\n"
            )
        if size == self.offset:
            return
        with self.path.open("rb") as f:
            f.seek(self.offset)
            data = f.read()
        self.offset += len(data)
        self.viewer.appendAnsiText(self.decoder.decode(data))


DEMO_LINES = [
    "\x1b[32mINFO \x1b[0m worker started (pid 4120)",
    "\x1b[36mDEBUG\x1b[0m polling queue 'jobs'",
    "\x1b[32mINFO \x1b[0m job 17 done in 220ms",
    "\x1b[33mWARN \x1b[0m job 18 retry 1/3",
    "\x1b[31mERROR\x1b[0m job 18 failed: connection reset",
]


def demo_writer(path: Path) -> QTimer:
    """Append a demo line to *path* every 600 ms."""
    count = iter(range(10**9))

    def write():
        n = next(count)
        with path.open("a", encoding="utf-8") as f:
            f.write(DEMO_LINES[n % len(DEMO_LINES)] + "\n")

    timer = QTimer(interval=600)
    timer.timeout.connect(write)
    timer.start()
    return timer


def build(path: Path) -> tuple[AnsiTextViewer, FileTail]:
    """Create a viewer following *path*."""
    viewer = AnsiTextViewer()
    viewer.setWindowTitle(f"tail -f {path}")
    return viewer, FileTail(viewer, path)


def main() -> None:
    """Follow the path given on the command line, or a demo file."""
    app = QApplication(sys.argv)
    if len(sys.argv) > 1:
        path, writer = Path(sys.argv[1]), None
    else:
        path = Path(tempfile.gettempdir()) / "qansitextviewer-demo.log"
        path.write_text("", encoding="utf-8")
        writer = demo_writer(path)
    viewer, tail = build(path)
    viewer.resize(820, 420)
    viewer.show()
    exit_code = app.exec()
    del writer, tail
    sys.exit(exit_code)


if __name__ == "__main__":
    main()

Your own highlight rules

Plain text with no ANSI codes can still be colored. Three small rules dim client addresses, color HTTP status codes by class, and bold every timing. See Highlighting for the rule protocol.

An access log with gray IP addresses, status codes colored green, blue, amber and red by class, and orange bold durations An access log with gray IP addresses, status codes colored green, blue, amber and red by class, and orange bold durations

An access log colored by three custom rules.
examples/custom_highlight.py
examples/custom_highlight.py
"""Add your own highlight rules: durations, HTTP status codes, IP addresses.

Run with ``uv run python examples/custom_highlight.py``. A rule is any
object with ``spans(text)`` that yields ``Span`` objects; it colors plain
log text that carries no ANSI codes of its own.
"""

import re
import sys
from collections.abc import Iterable

from PySide6.QtGui import QColor
from PySide6.QtWidgets import QApplication

from ansi_text_viewer import AnsiTextViewer
from ansi_text_viewer.highlight import Span


class DurationRule:
    """Bold orange for timings like ``41ms`` or ``2.5s``."""

    pattern = re.compile(r"\b\d+(?:\.\d+)?(?:ms|s)\b")

    def spans(self, text: str) -> Iterable[Span]:
        """Yield one span per duration in *text*."""
        for m in self.pattern.finditer(text):
            yield Span(m.start(), m.end(), foreground=QColor(214, 110, 0), bold=True)


class StatusRule:
    """HTTP status codes: 2xx green, 3xx blue, 4xx amber, 5xx red."""

    pattern = re.compile(r"\" ([1-5]\d\d) ")
    colors = {
        "2": QColor(0, 140, 60),
        "3": QColor(30, 100, 200),
        "4": QColor(190, 120, 0),
        "5": QColor(200, 30, 30),
    }

    def spans(self, text: str) -> Iterable[Span]:
        """Yield a bold span on the status code of an access-log line."""
        m = self.pattern.search(text)
        if m and m.group(1)[0] in self.colors:
            color = self.colors[m.group(1)[0]]
            yield Span(m.start(1), m.end(1), foreground=color, bold=True)


class IpRule:
    """Dim the client address so the request stands out."""

    pattern = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}")

    def spans(self, text: str) -> Iterable[Span]:
        """Yield a gray span over a leading IPv4 address."""
        m = self.pattern.match(text)
        if m:
            yield Span(m.start(), m.end(), foreground=QColor(120, 120, 120))


ACCESS_LOG = """\
10.0.0.12 - - "GET /api/v1/users HTTP/1.1" 200 1532 41ms
10.0.0.12 - - "GET /static/app.js HTTP/1.1" 304 0 3ms
192.168.4.7 - - "POST /api/v1/login HTTP/1.1" 401 88 120ms
10.0.0.31 - - "GET /api/v1/reports?year=2026 HTTP/1.1" 200 90210 2.4s
192.168.4.7 - - "GET /old-page HTTP/1.1" 301 0 2ms
10.0.0.44 - - "POST /api/v1/upload HTTP/1.1" 502 0 30.0s
10.0.0.12 - - "DELETE /api/v1/users/17 HTTP/1.1" 204 0 18ms
"""


def build() -> AnsiTextViewer:
    """Create a viewer with the three custom rules and a sample access log."""
    viewer = AnsiTextViewer()
    viewer.setWindowTitle("Custom highlight rules")
    # Access logs are full of URL paths that are not local files; keep the
    # built-in file and URL link rules from underlining them.
    viewer.setLinksEnabled(False)
    for rule in (IpRule(), StatusRule(), DurationRule()):
        viewer.add_highlight_rule(rule)
    viewer.appendAnsiText(ACCESS_LOG)
    return viewer


def main() -> None:
    """Show the highlighted access log."""
    app = QApplication(sys.argv)
    viewer = build()
    viewer.resize(820, 300)
    viewer.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

Open a huge log

Load hundreds of thousands of lines without freezing the window: appendAnsiTextAsync() inserts one chunk per event-loop turn, a progress bar follows asyncAppendProgress, and Cancel drops the rest. The example raises setMaximumBlocks(), since the default keeps only the newest 10,000 lines.

The big-file window after loading 60,000 generated lines: the end of the log, a full progress bar, and the status done, 60,000 lines The big-file window after loading 60,000 generated lines: the end of the log, a full progress bar, and the status done, 60,000 lines

60,000 generated lines, loaded in the background.
examples/big_file.py
examples/big_file.py
"""Open a huge log without freezing the window.

Run with ``uv run python examples/big_file.py path/to/huge.log``. Without a
path, it generates 200,000 colored lines. The text goes in through
``appendAnsiTextAsync()``, one chunk per event-loop turn, while a progress
bar follows along and Cancel stops the rest.
"""

import sys
from pathlib import Path

from PySide6.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QLabel,
    QProgressBar,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

from ansi_text_viewer import AnsiTextViewer

LEVELS = ["\x1b[32mINFO \x1b[0m", "\x1b[36mDEBUG\x1b[0m", "\x1b[33mWARN \x1b[0m"]


def synthetic_log(lines: int) -> str:
    """Return *lines* lines of colored sample log text."""
    return "".join(
        f"{LEVELS[i % 3]} request {i:>6} handled in {i % 97 + 3}ms\n"
        for i in range(lines)
    )


class BigFileWindow(QWidget):
    """A viewer, a progress bar, and a Cancel button."""

    def __init__(self):
        """Build the window and wire the async progress signals."""
        super().__init__()
        self.setWindowTitle("Big file")
        self.viewer = AnsiTextViewer()
        self.viewer.setMaximumBlocks(250_000)  # default keeps the newest 10,000
        self.progress = QProgressBar()
        self.status = QLabel("idle")
        self.cancel = QPushButton("Cancel", enabled=False)
        self.total = 0

        bar = QHBoxLayout()
        bar.addWidget(self.progress, 1)
        bar.addWidget(self.status)
        bar.addWidget(self.cancel)
        layout = QVBoxLayout(self)
        layout.addWidget(self.viewer)
        layout.addLayout(bar)

        self.viewer.asyncAppendProgress.connect(self.on_progress)
        self.viewer.asyncAppendFinished.connect(self.on_finished)
        self.cancel.clicked.connect(self.on_cancel)

    def load(self, text: str) -> None:
        """Queue *text* for non-blocking insertion."""
        self.viewer.clear()
        self.total = 0
        self.cancel.setEnabled(True)
        self.status.setText("loading...")
        self.viewer.appendAnsiTextAsync(text, chunk_lines=2000)

    def on_progress(self, done: int, total: int) -> None:
        """Mirror the async queue in the progress bar."""
        self.total = total
        self.progress.setMaximum(total)
        self.progress.setValue(done)
        self.status.setText(f"{done:,} / {total:,} lines")

    def on_finished(self) -> None:
        """Report completion."""
        self.cancel.setEnabled(False)
        self.status.setText(f"done, {self.total:,} lines")

    def on_cancel(self) -> None:
        """Drop whatever has not been inserted yet."""
        dropped = self.viewer.cancelAsyncAppends()
        self.cancel.setEnabled(False)
        self.status.setText(f"cancelled ({dropped} chunks dropped)")


def build() -> BigFileWindow:
    """Create the window."""
    return BigFileWindow()


def main() -> None:
    """Load the file named on the command line, or generated lines."""
    app = QApplication(sys.argv)
    window = build()
    window.resize(820, 480)
    window.show()
    if len(sys.argv) > 1:
        text = Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace")
    else:
        text = synthetic_log(200_000)
    window.load(text)
    sys.exit(app.exec())


if __name__ == "__main__":
    main()