Why does print with end='' doesn't appear until new line?

Viewed 629

I have been making a program in python 3.9 and after having this code:

#Print 3 dots at the interval shown
def dots(t):
    t *= 3
    sleep(t)
    print('.', end='')
    sleep(t)
    print('.', end='')
    sleep(t)
    print('.')

And this calling it:

# These are completely aesthetic
sleep(0.25)
print("Defining Functions", end='')
dots(0.4)

I expected for the program to print Defining Functions and after 1.2 seconds, 3 times, add a dot(.) at the end. What really happened is after 3.85 seconds it printed the whole thing altogether with dots(Defining Functions...). So it has not printed anything until a new line is added(3rd dot).

Sorry if it's messy, I don't know how to make these questions well

2 Answers

Python buffers output to stdout. This is because writing larger pieces of text at a time is more efficient (less syscalls).

By default, if stdout is connected to a terminal, the output will be line-buffered. Thus printing a newline flushes the buffer and you see the output immediately. If stdout is redirected into a pipe or file, Python buffers even more aggressively and will not flush on newlines, only when the buffer is full.

To avoid this problem, flush the buffer explicitly before sleeping:

 print('.', end='', flush=True)

Pass flush=True to the print

def dots(t):
    t *= 3
    sleep(t)
    print('.', end='', flush=True)
    sleep(t)
    print('.', end='', flush=True)
    sleep(t)
    print('.', flush=True)

sleep(0.25)
print("Defining Functions", end='', flush=True)
dots(0.4)

And you may ask why print behaves like this, printing something is not a very fast and straight thing to do for most of the programming languages, python is waiting to print everything only once to be more efficient, but you can specifically tell it to flush your messages right away without waiting for other prints.

Related