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

Time:10-07

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.

CodePudding user response:

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='')

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

Try it:

import sys
import time

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