How do I print to console in pytest?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Printing to Console in pytest
When using `pytest` for writing and executing tests, directly printing to the console can sometimes be challenging, especially if you want to see those outputs during normal test runs. This article discusses various approaches to effectively print to console when working with `pytest`.
Why Printing in `pytest` Isn't Straightforward
In `pytest`, print statements are captured by default, meaning that they can be suppressed in the final test output. This is done to keep the output clean and readable, primarily focusing on the results of the tests themselves. However, seeing print outputs can be useful, particularly for debugging or logging.
Default Behavior
By default, `pytest` captures output from Python’s `sys.stdout` and `sys.stderr` streams and presents them only when a test fails. This means regular print statements do not appear in the output for passing tests.
Approaches to Print in Pytest
Here are several methods to print to the console when using `pytest`:
1. Using the `-s` Option
Running pytest with the `-s` option disables all output capturing, allowing print statements to display as usual:
- `capsys`: Captures output from `sys.stdout` and `sys.stderr`.
- `capfd`: Captures output at the file descriptor (fd) level.
Related reading
- How do I redeploy everything in kubernetes after updating a dockerfile?
- How do I reference cross-stack resources in the same app?
- How do I remove the Kubernetes dashboard resources from my deployment on Google Cloud Platform?
- How do I run a command on an already existing Docker container?
- How do I print to stderr in Python?
- How do I profile a Python script?
- How do I properly assert that an exception gets raised in pytest?
- How do I properly assert that an exception gets raised in pytest?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.