jmwalker0498
jmwalker0498

Reputation: 3

Why isn't sys.stdout.flush() printing all the characters on the same line?

Here's my code:

wait = "..."
for char in wait:
   sys.stdout.flush()
   time.sleep(1)
   print(char)

I'm trying to get it to ouput:

...

But instead it outputs:

.
.
.

I don't understand why sys.stdout.flush has no effect.

Upvotes: 0

Views: 1311

Answers (4)

Ramael
Ramael

Reputation: 134

Try it:

import sys
import time

wait = "..."
for char in wait:
    time.sleep(1)
    print(char, end="", file=sys.stdout, flush=True)

Upvotes: 0

VPfB
VPfB

Reputation: 17237

If you type help(print) in the Python interpreter, you'll get:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Using this information:

for char in wait:
   time.sleep(1)
   print(char, end='', flush=True)

Upvotes: 3

Tom McLean
Tom McLean

Reputation: 6297

std.out.flush() just writes whats in the buffer onto the screen

By default, print() adds a \n to the end to write a new line. You can turn it off by doing print(s, end='')

Upvotes: 1

Bhagyesh Dudhediya
Bhagyesh Dudhediya

Reputation: 1856

Using parameter end='' in print you can achieve the desired results:
Try out this:

import sys
import time
wait = "..."
for char in wait:
   sys.stdout.flush()
   time.sleep(1)
   print(char, end='')

You can read more about the end parameter here

Upvotes: 0

Related Questions