How to print characters without a new line, inside a while loop, and with sleep?

Viewed 22

I just realised, I can't print a character, on the same line with a delay.

import sys
import time
while True:
  sys.stdout.write('.')
  time.sleep(3.0)    

I can only see the result after I break the loop with CTRL+C. Is there a solution for that?

I would like to see each point being printed ....., with a delay.

2 Answers

Output is probably buffered, it would eventually output to the terminal after the buffer was filled, but if you want it to be shown immediately you should explicitly flush output:

sys.stdout.flush()

in your loop

You can do this in one command in python 3:

print(".", end='', file=sys.stdout, flush=True) 

here is a sample how it can be done. print() has a parameter that can be set like: flush=True:

from time import sleep
count = 0
while count < 20:
    print('.', end='', flush=True) # prints all in one line
    #print('.', flush=True) # prints on separate lines
    sleep(1)
    count += 1
Related