Allan Burleson Allan Burleson - 1 month ago 13
Python Question

Why does the print function stop working with sleep with the end argument?

I was just messing around and I have the following code:

from time import sleep
while True:
print('a', end=' ')
sleep(0.05)


For some reason, nothing is printed until I press Ctl+C. Then it prints everything it should have been continually printing. However, if I remove the
end
argument:

from time import sleep
while True:
print('a')
sleep(0.05)


It works perfectly. "a" prints every 0.05 seconds.

Also, I don't have the problem with the first code when I leave out
sleep
.

So: Why does the
end
argument make
sleep
hide output?

Answer

When Python (and other) programs print to the screen, it is first send to a print buffer. When Python find it fittingly, it will flush this buffer onto the screen. I do not know the internal details of this behavior, but you can set the flush keyword of the print function to True to force the flush to happen instantly. Try:

from time import sleep
while True:
    print('a', end='        ', flush=True)
    sleep(0.05)
Comments