Search code examples
pythonsleep

Strange print behavior with time.sleep in python


I was trying to create a progress-like thing by printing a dot every second on the same line. Something like "Fishing.....". This is what I used:

import time

print('Fishing', end='')
for i in range(5):
    time.sleep(1)
    print('.', end='')

But it waits for 5 seconds and prints Fishing..... all at once. But when I don't use the end='', it prints dots every second, but on separate lines like so

Fishing.
.
.
.
.

My questions:

  1. Why does print behave this way?
  2. How can I print a dot every second, but on the same line?

Solution

    1. Why does print behave this way?

    This has less to do with print and more with your terminal. For performance reasons, the text only gets "flushed" everytime there's a newline character, and not one character at a time.

    1. How can I print a dot every second, but on the same line?

    By "flushing" the standard output manually everytime you printed something:

    import time
    import sys
    
    print('Fishing', end='')
    sys.stdout.flush()
    for i in range(5):
        time.sleep(1)
        print('.', end='', flush=True)  # another way
    

    If you need this all the time, you could define a seperate flushing print function:

    from functools import partial
    myprint = partial(print, end='', flush=True)
    myprint('Fishing')
    for i in range(5):
        time.sleep(1)
        myprint('.')