Reputation: 13
I tried to write this script that just prints number after each other on the same line with a one second delay, but it does not work.
Ex this works:
from time import sleep
for n in range(1, 11):
print(n)
sleep(1)
But this does not, the program just freezes:
from time import sleep
for n in range(1, 11):
print(n, end="")
sleep(1)
Can anyone explain why this is?
Upvotes: 1
Views: 46
Reputation: 160407
The program does not freeze, you just need to flush the stream by passing flush=True
:
print(n, end="", flush=True)
sys.stdout
, the stream that print
uses by default, is line-buffered (when in interactive mode), as stated in the documentation:
- When interactive, standard streams are line-buffered
This means that when the default string used for end
(\n
) is encountered, a call to flush
will be made. Using other strings (i.e ''
) don't trigger flush
ing so you'll have to force it by using flush=True
.
Upvotes: 2