0

I'm trying to make a little animation type thing where it prints R then waits for .5 seconds the o then waits for .5 seconds and so on until the end. Here is the code I wrote:

import time
def rolling():
    print('R', end = '')
    time.sleep(.5)
    print('o', end = '')
    time.sleep(.5)
    print('l', end = '')
    time.sleep(.5)
    print('l', end = '')
    time.sleep(.5)
    print('i', end = '')
    time.sleep(.5)
    print('n', end = '')
    time.sleep(.5)
    print('g', end = '')
    time.sleep(.5)

When I run that it waits for 3.5 seconds and then prints the whole word. Any suggestions?

Sam_Cameron
  • 105
  • 2
  • 11
  • stdout is buffered; see https://eklitzke.org/stdout-buffering for some details on this topic. – larsks May 01 '20 at 20:39
  • 1
    You got me curious, so I googled. add ```flush=True``` arg to each ```print``` and it does what you want, ie. ```print('R', end = '', flush=True)```. Found answer on SO here: https://stackoverflow.com/questions/5598181/multiple-prints-on-the-same-line-in-python – pink spikyhairman May 01 '20 at 20:46

1 Answers1

2

The output of your program is line buffered (as is in any common scenario), therefore, since you are not printing any newline (\n), the result is only written to the console at the end of execution, all at once.

To ensure each call to print() immediately produces an output, you can add flush=True (thank you pink spikyhairman for pointing this out, I was unaware of the feature at the time of writing the original answer):

import time

def rolling():
    print('R', end = '', flush=True)
    time.sleep(.5)
    print('o', end = '', flush=True)
    time.sleep(.5)

You could even directly go with sys.stdout.write() and .flush() instead:

import time
import sys

def rolling():
    sys.stdout.write('R')
    sys.stdout.flush()
    time.sleep(.5)
    sys.stdout.write('R')
    sys.stdout.flush()
    time.sleep(.5)
    # ...
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128