Search code examples
pythonpython-3.xtimepython-3.6sleep

Why does time.sleep() happen all at once instead of one at a time?


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?


Solution

  • 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)
        # ...