1

Here is my code:

import time as t

print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)

My problem is that all the print commands are executed after the sleep commands, and that's not my intended output.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • Where are you printing to? I cannot reproduce, but there is a buffer for `stdout` and likely it's not getting flushed. – roganjosh Mar 14 '19 at 19:57
  • I mean, have you directed stdout somewhere? This should print fine to a console. – roganjosh Mar 14 '19 at 19:59
  • Do you mean that it takes three seconds then prints hello three times? Because it printed hello three times with a one second break between for me –  Mar 14 '19 at 19:59
  • @JonathanDyke It printed all at the end for me. – Barmar Mar 14 '19 at 20:00
  • I just ran it in a jupyter notebook as I had one open I don't know if that changed anything –  Mar 14 '19 at 20:00
  • 1
    There is an optional `flush` parameter to `print()` in Python 3. If you add `flush=True`, `print` should print immediately. – khelwood Mar 14 '19 at 20:01
  • 1
    Closely related: [How to flush output of print function?](//stackoverflow.com/q/230751) – Aran-Fey Mar 14 '19 at 20:02

1 Answers1

7

It's because of output buffering. The buffer isn't flushed until a newline is printed. Since you used end=' ', there's no newline after each word, so the buffer isn't flushed until the script ends.

You can use the flush=True option to force it to flush immediately.

import time as t
import sys

print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)
Barmar
  • 741,623
  • 53
  • 500
  • 612