Josef-Friedrich / stdout_stderr_capturing

Capture the stdout or stderr output as a list in a context manager block (with).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

This package on the Python Package Index Tests

stdout_stderr_capturing

Capture the stdout or stderr output as a list in a context manager block (with).

Maybe better alternatives:

With Python 3:

from io import StringIO
from contextlib import redirect_stdout, redirect_stderr

stdout = StringIO()
stderr = StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
    print('Test')
    stdout.getvalue()
    stderr.getvalue()

Using pytest

def test_myoutput(capsys):  # or use "capfd" for fd-level
    print("hello")
    sys.stderr.write("world\n")
    captured = capsys.readouterr()
    assert captured.out == "hello\n"
    assert captured.err == "world\n"
    print("next")
    captured = capsys.readouterr()
    assert captured.out == "next\n"

Capture stdout:

with Capturing() as output:
    print('line 1')

print(output[0])

is equivalent to

with Capturing(stream='stdout') as output:
    print('line 1')

Capture stderr:

with Capturing(stream='stderr') as output:
    print('line 1', file=sys.stderr)

About

Capture the stdout or stderr output as a list in a context manager block (with).

License:MIT License


Languages

Language:Python 92.5%Language:Makefile 7.5%