How to Test Printed Output in Python with Pytest and its Capsys Fixture

Pavol Kutaj
1 min readMay 24


The aim of this page📝 is to investigate methods for succesfully testing a print statement output in pytest.

Testing a simple statement is simple: use capsys fixture and readouterr().out

To test the last out of multiple printed commands, split captured string and select via expected position

  • the function test_my_function takes one argument, capsys, which is a built-in pytest fixture that captures the output to stdout and stderr.
  • inside the function, we call my_function(), which presumably prints multiple outputs.
  • use the readouterr() method of the capsys fixture to capture the outputs.
  • this method returns a named tuple with two attributes: out and err, which contain the captured output to stdout and stderr, respectively.
  • split the captured output by newline characters to get a list of all individual outputs.
  • get the last output by indexing the list with -1.
  • finally, use an assertion to check if the last output is equal to the expected value.

If I don’t know the exact position of the printed command, I am using the in operator

  • the following also uses a monkeypatch fixture for simulating three inputs that the script takes
  • the script is a command composer of a Hashicorp Vault wrapper setting a secret

LINKS How to capture stdout/stderr output — pytest documentation



Pavol Kutaj

Infrastructure Support Engineer/Technical Writer ( with a passion for Python/writing documentation. More about me: