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.

7
  • Where are you printing to? I cannot reproduce, but there is a buffer for stdout and likely it's not getting flushed. Commented Mar 14, 2019 at 19:57
  • I mean, have you directed stdout somewhere? This should print fine to a console. Commented Mar 14, 2019 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 Commented Mar 14, 2019 at 19:59
  • 1
    There is an optional flush parameter to print() in Python 3. If you add flush=True, print should print immediately. Commented Mar 14, 2019 at 20:01
  • 1
    Closely related: How to flush output of print function? Commented Mar 14, 2019 at 20:02

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

7 Comments

This won't give the desired behaviour though, I don't think. I can get the output fine and on a single line being sequentially built
@ChristianDean Just discovered that myself, was about to edit
Gotcha @Barmar.
print('hello\n', end=' ') why this one work correct? what does new line work in print??
Because you're writing a newline to the output buffer @mohamadmahdireisi, causing it to be flushed.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.