Skip to content

printing

langroid/utils/output/printing.py

PrintColored(color)

Context to temporarily print in a desired color

Source code in langroid/utils/output/printing.py
def __init__(self, color: str):
    self.color = color

print_long_text(color, style, preamble, text, chars=None)

Print text (possibly truncated) after preamble, in the given color/style.

text is printed literally: neither Rich markup nor terminal escape sequences in it are interpreted.

Source code in langroid/utils/output/printing.py
def print_long_text(
    color: str, style: str, preamble: str, text: str, chars: Optional[int] = None
) -> None:
    """Print `text` (possibly truncated) after `preamble`, in the given color/style.

    `text` is printed literally: neither Rich markup nor terminal escape
    sequences in it are interpreted.
    """
    # Strip first, so that `chars` counts printable characters and a truncation
    # boundary cannot fall inside an escape sequence.
    text = text.translate(_STRIP_CONTROL_CHARS)
    if chars is not None:
        text = " ".join(text.split())
        text = text[:chars] + "..." + text[-chars:] if len(text) > 2 * chars else text
    # `text` can be ingested document content or LLM output, so it must not
    # reach Rich's markup parser. Pass it as a `Text` renderable rather than
    # interpolating it into the markup string: `Text.__str__()` is the plain
    # underlying text, so an f-string would hand any `[...]` sequences in it --
    # including terminal-hyperlink tags -- straight to that parser. Escaping
    # the string instead is not enough, because `Text` strips some control
    # characters afterwards, which can re-form a tag the escaping had
    # neutralized. Only `preamble`, `color` and `style`, which callers supply,
    # are treated as markup.
    #
    # Note that printing it as a renderable is also what makes the control-char
    # stripping above load-bearing: a raw escape sequence interpolated into the
    # markup string used to be broken up by Rich's highlighter, which hid this
    # route by accident rather than by design.
    styled_text = Text(text, style=color)
    if style:
        # Layered as a separate span rather than concatenated into one style
        # string, so that `color` and `style` are each resolved on their own
        # (a theme style name such as "repr.number" does not resolve as one
        # word of a longer style string).
        styled_text.stylize(style)
    rprint(f"[{color}]{preamble}", styled_text)

silence_stdout()

Temporarily silence all output to stdout and from rich.print.

This context manager redirects all output written to stdout (which includes outputs from the built-in print function and rich.print) to /dev/null on UNIX-like systems or NUL on Windows. Once the context block exits, stdout is restored to its original state.

Example

with silence_stdout_and_rich(): print("This won't be printed") rich.print("This also won't be printed")

Note

This suppresses both standard print functions and the rich library outputs.

Source code in langroid/utils/output/printing.py
@contextmanager
def silence_stdout() -> Iterator[None]:
    """
    Temporarily silence all output to stdout and from rich.print.

    This context manager redirects all output written to stdout (which includes
    outputs from the built-in print function and rich.print) to /dev/null on
    UNIX-like systems or NUL on Windows. Once the context block exits, stdout is
    restored to its original state.

    Example:
        with silence_stdout_and_rich():
            print("This won't be printed")
            rich.print("This also won't be printed")

    Note:
        This suppresses both standard print functions and the rich library outputs.
    """
    platform_null = "/dev/null" if sys.platform != "win32" else "NUL"
    original_stdout = sys.stdout
    fnull = open(platform_null, "w")
    sys.stdout = fnull
    try:
        yield
    finally:
        sys.stdout = original_stdout
        fnull.close()