Why does time.sleep wait sometime, but other times it "jumps to the end"

Question:

Why does time.sleep work with print(“=”), but not with print(“=”, end=””)?

I just started with Python and this problem just doesnt make first glace sense: I want to make a line appear with some sort of animation. The first code (1) works well, but doenst output the ==== line i want. The second one (2) instantly prints ==== after waiting for all the timers to finish…:

Am i missing something?

#first

import time
for x in range(10):
    print("=")
    time.sleep(0.2)

#second

import time
for x in range(10):
    print("=", end="")
    time.sleep(0.2)

The first one output:

=

=

=

With expected 0.2seconds delay but each = in a new line

the second one outputs:

======

after waiting for 2 seconds

Expected:

=====

with a .2 delay between each “=”

Nevermind, i figured it out a workaround:

for x in range(10):
    print("="*x, end="r")
    time.sleep(0.1)

The better solution:

for x in range(10):
    print("="*x, end="r")
    sys.stdout.flush()
    time.sleep(0.1)

# Or

for x in range(10):
    print("="*x, end="r", flush=True)
    time.sleep(0.1)
Asked By: M. Krabs

||

Answers:

This is not a problem with time.sleep. Your script does actually pause for the indicated time of 200 ms. However, the output (of whatever terminal you’re running this in) is apparently buffered, which is typically the case. You can usually circumvent the buffering by passing flush=True as an argument to the print function.

So

print("=", end="")

should be

print("=", end="", flush=True)

instead.

Answered By: john-hen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.