Reputation: 422
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:
print('Done!')
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:
.......Done!
How can I force Python to print on the same line step after step?
Upvotes: 3
Views: 480
Reputation: 1121894
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.
Upvotes: 10
Reputation: 2089
for python 2.7.3 you can left a trailing comma which tells the idle to not insert a line after the statement is printed for example
print "hello",
print "world"
would return
>>> hello world
Upvotes: 0
Reputation: 8411
Instead of using print, you can write directly to stdout, (unbuffered):
import sys
import time
for i in range (10):
time.sleep (0.5)
sys.stdout.write('.')
print 'Done!'
Upvotes: 2