pytest
console output
stdout
stderr
python debugging

How to see normal stdout/stderr console print output from code during a pytest run?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In this article, we will explore how to view the standard output (stdout) and standard error (stderr) console print outputs from code during a pytest run. pytest is a widely used testing framework in Python, and one of the challenges developers face is accurately capturing and viewing print statements during test executions. By default, pytest captures these outputs and suppresses them, but there are several ways to configure and override this behavior.

Understanding pytest's Output Capture

By default, pytest captures all output generated by tests to ensure clean and readable test results. This includes:

  • stdout - Standard output from print() functions and other standard library functions that write to standard output.
  • stderr - Standard error from warnings or errors.

The captured output is only displayed when a test fails to allow developers to easily diagnose the issue. However, for debugging and development purposes, it may be desirable to view all outputs regardless of the test outcomes.

Methods to Access stdout/stderr Prints

1. Using the -s Flag

The simplest way to view print outputs is to use the -s flag when you run your tests. This disables output capturing entirely:

bash
pytest -s

With this option, both print() statements and errors will be visible in the console in real-time as the tests execute.

2. Using the --capture=no Option

Equivalent to -s, the --capture=no option stops any output capturing:

bash
pytest --capture=no

This command serves the same purpose as pytest -s.

3. Capturing Output for Specific Tests

pytest also allows capturing or uncapturing outputs for specific tests using fixtures such as capsys or capfd.

Example with capsys

capsys can be used to capture both stdout and stderr outputs during the test's execution:

python
1def test_example(capsys):
2    print("Hello, World!")
3    out, err = capsys.readouterr()
4    assert out == "Hello, World!\n"
5    assert err == ""

Key Points:

  • capsys.readouterr() returns a tuple of the captured standard output and standard error.
  • Useful for testing what exactly was printed during the test.

Example with capfd

capfd works similarly, but specifically interacts with file descriptors, which is useful for cases involving native C extensions:

python
1def test_example(capfd):
2    print("Output through file descriptor")
3    out, err = capfd.readouterr()
4    assert out == "Output through file descriptor\n"
5    assert err == ""

4. Configuring pytest INI Defaults

You can configure default capturing behavior in the pytest.ini file as follows:

ini
# pytest.ini
[pytest]
addopts = --capture=sys
  • sys: captures using Python's sys.stdout and sys.stderr.
  • fd: captures by using file descriptors instead of sys.stdout/sys.stderr.
  • no: disables all capturing by default.

5. Command-Line Redirection

For tailored running scenarios, outputs can be redirected to external files directly from the command line:

bash
pytest > test_log.txt 2>&1

This command will redirect both standard output and error output to test_log.txt.

6. Disabling Capturing in Specific Tests

You can also disable capturing within specific test functions by using pytest's decorator:

python
1import pytest
2
3@pytest.mark.usefixtures('capfd_disabled')
4def test_example():
5    print("This will print to the console directly.")
6
7@pytest.fixture
8def capfd_disabled(capfd):
9    capfd.close()

Summary Table

To provide a concise overview of different approaches, consider the following table:

ApproachCommand / Example CodeDescription
Disable with -s Flagpytest -sDisables capturing entirely. Real-time output.
Use --capture=no Optionpytest --capture=noEquivalent to -s. Disables capturing entirely.
capsys Fixturedef test_func(capsys): ...Captures stdout/stderr in tests.
capfd Fixturedef test_func(capfd): ...File descriptor based capturing.
pytest.ini Configuration[pytest] addopts = --capture=sysSets capture mode globally.
Command-Line Redirectionpytest > log.txt 2>&1Redirects output to external files.
Disable Capturing SpecificUse @pytest.mark.usefixtures(capfd_disabled) decoratorDisables capturing only for specific tests.

Keeping in mind these methods allows developers to better manage test outputs, making it easier to troubleshoot, develop and maintain testing infrastructure with pytest. Each method suits different scenarios, and selecting the right one depends on specific testing needs and goals.


Course illustration
Course illustration

All Rights Reserved.