How can I flush the output of the print function?
To get immediate print output, use flush=True
:
To apply flushing to a custom print function:
For Python versions prior to 3.3, flush output manually:
Applying unbuffered output to scripts
You can run your script with the -u
flag for unbuffered output on-all-the-time:
To globally unbuffer session, use PYTHONUNBUFFERED
environment variable:
Judicious use of sys.stdout
Understanding sys.stdout
is pivotal as it's connected to the standard output. By default, sys.stdout
is line-buffered. This means it's flushed when a newline char is printed. Full buffering flushes only when the buffer is full. If you need immediate output, flushing is essential.
Nifty tricks to boost print output
Redefining print in Python 2
You can automatically include flushing within the print
function:
Module-wide auto-flush with functools.partial
Modify print
across entire module using functools.partial
, can be handy in debugging.
Redirect the course of print output
Print output can flow to different streams using the file
argument:
Customize your print outs
Use sep
and end
to customize output formatting:
Caveats to watch out for
- Script exécution speed: Consistent flushing can put brakes on your script due to reduced buffering efficiency.
- I/O blocking: In case the script is writing to an output that can block, over flushing could lead to script hanging until the I/O operation is complete.
- Resource management: Output without buffering translates to more write operations to the file or terminal which is resource-wise less efficient.
Was this article helpful?