Pierre Pierre - 21 days ago 4x
Python Question

Print on the same line, step after step

I've developed a Python script that performs several tasks in a row (mainly connecting to servers and retrieving information).

There are many steps, and for each of them I would like to display a dot, so that the user knows there is something going on.

At the end of each step, I do:

print('.', end='')

And in the final step, I write:


It works, except nothing is displayed until the final print is executed, so it kind of defeats its original purpose :)

Basically, nothing is displayed on the screen, and at the very last moment, this pops up:


How can I force Python to print on the same line step after step?


By default, stdout is line buffered, meaning the buffer won't be flushed until you write a newline.

Flush the buffer explicitly each time you print a '.':

print('.', end='', flush=True)

The flush keyword was added in Python 3.3; for older versions, use sys.stdout.flush().

From the print() function documentation:

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

and from the sys.stdout documentation (the default value for the file argument of the print() function):

When interactive, standard streams are line-buffered. Otherwise, they are block-buffered like regular text files.