2

What I'm trying to do is add a delay of 0.5 seconds everytime it prints something. But the problem I have is that it lags for a while and then prints it all at once.

import time

x = [(0, 1), (2, 3), (4, 5), (6, 7), (8, 7)]

for i in x:
    print(i)
    time.sleep(0.5)

what this should do:

(0, 1)
wait 0.5 seconds
(2, 3)
wait 0.5 seconds
(4, 5)
etc

however the problem with mine is that it doesnt print the first one and wait 0.5 and print the next, what mine does is it waits for so long and then prints all at once, I was wondering what's a way to fix this.

Sc4r
  • 700
  • 1
  • 10
  • 15

3 Answers3

5

Some systems buffer until a line break. That's probably what you are seeing.

yonili's answer should do the trick. Add sys.stdout.flush() after each print statement.

EDIT:

For what it's worth, pasting the code into ipython on my linux machine gives the output below, printed with a half second delay between each line.

(0, 1)
(2, 3)
(4, 5)
(6, 7)
(8, 7)
Morten Jensen
  • 5,818
  • 3
  • 43
  • 55
  • 1
    Thanks this seemed to have solved this. But it's a strange issue I tried the same thing using idle and it worked. I guess the IDE that I'm using is acting weird. – Sc4r Feb 22 '14 at 21:02
2

Try adding sys.stdout.flush() after the print

yonili
  • 703
  • 5
  • 18
1

It appears you're using Python 3, so you actually can do this without any additional statements. Just add flush=True to your print statement's parameters, ie:

print(i, flush=True)

I was having the same problem getting a loading bar to work in Python, and this fixed it.

user3030010
  • 1,767
  • 14
  • 19