Skip to content
Advertisement

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

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.

Advertisement

Answer

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) 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement