I can not understand how the flush works in python's print.
I can not understand how the flush works in python's print.
The print
uses stdout
, like C. This is nothing more than the "file" in the operating system where the text output of a program is sent, and thus can be shown to the user. p>
By default, stdout
is buffered; that is, it stores the data it receives without showing it until it receives the special newline code \n
.
The print
function of Python automatically automatically boosts a newline character in any string you send to it. But sometimes this behavior is not desired and you want to use two prints
to show something on the same line. In this case, you will use the end
argument of the print
function to end the string with something other than the newline character (or with an empty string, so that you do not print anything other than what you ordered).
For example, you can expect the following code to print several dots on the same line, one every 0.5s:
import time
for _ in range(5):
print('.', end='')
time.sleep(0.5)
print(' Pronto!')
But what really happens in most cases is that nothing happens for 2.5s and then all the dots appear at once.
This happens because stdout
by default shows nothing until it receives a new line, which we are not sending until the end.
So how do we remedy this problem?
Simple, just use flush
to force the result to appear immediately, even without a new line:
import time
for _ in range(5):
print('.', end='', flush=True)
time.sleep(0.5)
print(' Pronto!')
It is worth mentioning that flush
as argument pro print
is only available from Python 3.3. Before that, it had to be called manually:
import sys
import time
for _ in range(5):
print('.', end='')
sys.stdout.flush()
time.sleep(0.5)
print(' Pronto!')