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

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()