How to Check if Python's Output Buffering Is Enabled2020-06-26
By default, Python buffers output to standard output (stdout) and standard error (stderr). This means that output from your code might not show up immediately, making debugging harder.
To disable output buffering, you can run Python with the
-u option or by setting the
However, there’s no documented way of checking if output buffering is enabled from within Python.
It’s possible to detect it by checking
sys.stdout, which is an
This takes one argument, a buffered text stream to wrap, which you can access at
When output buffering is enabled,
sys.stdout.buffer will be an
When output buffering is disabled,
sys.stdout.buffer will the underlying
Some programs wrap
sys.stdout with extra layers, for example pytest does so to capture output.
To guard against these situations, you should instead check
sys.__stdout__ object, which holds the original value for
sys.stdout when Python started.
So an accurate check for output buffering would check if
sys.__stdout__ uses a
May your buffering problems be over,
Are your Django project's tests slow? Read Speed Up Your Django Tests now!
One summary email a week, no spam, I pinky promise.
- How to Combine Two Python Decorators
- Setting Python's Decimal Context for All Threads
- Entering a Flaky Context Manager in Python
© 2020 All rights reserved.