Skip to content

Instantly share code, notes, and snippets.

Last active March 30, 2023 11:18
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Script that captures both stdout and stderr in a way that works for subprocesses, while still being able to use rich own console to use original streams.
from rich.console import Console
from subprocess import run
import tempfile
import sys
from contextlib import redirect_stdout, redirect_stderr
# If we do not pass file=sys.stdout explicitly, rich output will also be
# captured by the context manager.
console = Console(file=sys.stdout)
console_err = Console(file=sys.stderr, stderr=True)
# We cannot use StringIO because the do not have a file descripor, which is
# needed for subprocesses.
captured_stdout = tempfile.TemporaryFile(mode="w+", prefix="stdout")
captured_stderr = tempfile.TemporaryFile(mode="w+", prefix="stderr")
with redirect_stdout(captured_stdout) as stdout:
with redirect_stderr(captured_stderr) as stderr:
console.print("[red]Hello[/], stdout world!")
console_err.print("[red]Hello[/], stderr world!")
"echo 'subprocess-stdout' && echo 'subprocess-stderr' >&2",
print("print-stderr", file=sys.stderr)
print("captured-stdout: %s" % captured_stdout.readlines())
print("captured-stderr: %s" % captured_stderr.readlines())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment