Does "time.sleep()" not work inside a for loop with a print function using the "end" attribute? Does "time.sleep()" not work inside a for loop with a print function using the "end" attribute? python-3.x python-3.x

Does "time.sleep()" not work inside a for loop with a print function using the "end" attribute?


As python is linebuffered it will wait for a newline before printing the stdout.

Solution 1:

Add PYTHONUNBUFFERED=1 to your env.var:

export PYTHONUNBUFFERED=1

This will allow the output to be immediately dumped

Solution 2:

As you are using python 3 you can use the flush=True

for i in range(50):    sleep(0.1)    print("#", end = '', flush=True)


I just found a solution on reddit.

reddit comment on why it doesn't work and how beginners fall into the same pitfall

So, it has something to do with buffering.

Here's the code that would work;

from time import sleepprint("starting the progress bar")for i in range(50):    sleep(0.1)    print("#", end = '', flush = True)


By default, Python is linebuffered. As long as you print without a newline, output is collected but not shown. You must forcefully flush the output.

from time import sleepprint("starting the progress bar")for i in range(50):    sleep(0.1)    print("#", end = '', flush=True)

Note in that whatever you use to view the output might be linebuffered as well. This cannot be changed from within your script.