Reputation: 111
So, I'm just recently learning python and I was playing with some code. I wanted to print the some character without line breaks over a loop with some delay. I used the time.sleep() function inside the for loop. But, all it does is delay the output for the total time it would have taken in the loop, all at once and, then print out the character.
I did try it without the "end" attribute and it worked perfectly. But, I didn't want the line break.
from time import sleep
print("starting the progress bar")
for i in range(50):
sleep(0.1)
print("#", end = '')
I expected the output to print a character and with a delay, print another character. But, the script delays for 0.1 seconds for 50 times and then prints out all the characters at once
Upvotes: 9
Views: 12596
Reputation: 1
I had the same problem. Just add import time above the code. I was coding a count down system-
import time
for i in range(10,0,-1):
print(i)
time.sleep(1)
print("yayy! the code works")
Upvotes: -1
Reputation: 1876
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)
Upvotes: 12
Reputation: 3898
You can use the -u
option when running your program.
$ man python3
PYTHON(1) PYTHON(1)
...
-u Force the stdout and stderr streams to be unbuffered. This
option has no effect on the stdin stream.
Run like this: python3 -u file.py
Alternatively, you can set the PYTHONUNBUFFERED
environment variable in your shell
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to speci-
fying the -u option.
Like so: PYTHONUNBUFFERED="yes" python3 file.py
Lastly, you can use flush=True
as other answers have mentioned.
Upvotes: 1
Reputation: 50076
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 sleep
print("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.
Upvotes: 1
Reputation: 111
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 sleep
print("starting the progress bar")
for i in range(50):
sleep(0.1)
print("#", end = '', flush = True)
Upvotes: 1