Skip to content

Color command output in docs? #2399

Open
@henryiii

Description

@henryiii

Should we color the command output in docs? As a proof of concept, I ran this in 3.14 with the following hack:

build.py

import os
import re
import subprocess
import sysconfig
from typing import Any

import rich.console
import rich.text


def define_env(env: Any) -> None:
    "Hook function for mkdocs-macros"

    @env.macro  # type: ignore[misc]
    def subprocess_run(*args: str) -> str:
        "Run a subprocess and return the stdout"
        env = os.environ.copy()
        scripts = sysconfig.get_path("scripts")
        env["PATH"] = f"{scripts}{os.pathsep}{env.get('PATH', '')}"
        env["PYTHON_COLORS"] = "1"
        output = subprocess.run(args, check=True, capture_output=True, text=True, env=env).stdout
        rich_text = rich.text.Text.from_ansi(output)
        console = rich.console.Console(record=True)
        console.print(rich_text)
        page = console.export_html(inline_styles=True)
        text = re.search(r"<body.*?>(.*?)</body>", page, re.DOTALL | re.IGNORECASE).group(1)
        return text.strip()

Result:

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions