1

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?

Neithan
  • 395
  • 1
  • 4
  • 9

1 Answers1

2

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)
jmd_dk
  • 12,125
  • 9
  • 63
  • 94