0

I'm trying to use the sleep function to have a delay between iterations in a loop but the loop executes all at once without delays.

from time import sleep


for i in range(5):
    print (i)
    sleep(0.5)

I tried doing it without a loop and the same problem, prints all the text instantly:

from time import sleep

print('hi')
sleep(2)
print('hi')
sleep(2)
print('hi')
sleep(2)

Edit: The issue is indeed output buffering. Adding sys.stdout.flush() after every print line fixed the issue.

Alan Navai
  • 49
  • 11
  • Can't reproduce…this puts a short delay between the prints in both v3 and v2.7 for me. – Mark Jul 13 '19 at 04:45
  • No it doesn't! Time your code using [timeit](https://docs.python.org/3/library/timeit.html) and you will see it takes 6 seconds – Devesh Kumar Singh Jul 13 '19 at 04:46
  • It's working for me, but in definitely doesn't take 6 seconds @DeveshKumarSingh – Mark Jul 13 '19 at 04:47
  • Why ? The sleep is for a total of 6 seconds right, so it should take 6 seconds? – Devesh Kumar Singh Jul 13 '19 at 04:51
  • @DeveshKumarSingh Could there be something wrong with my output console then? because I'm definitely seeing the output come all at once after a delay – Alan Navai Jul 13 '19 at 04:54
  • 1
    @AlanNavai There is definitely some crucial information missing from your question. –  Jul 13 '19 at 04:56
  • @DavidCullen Apologies but I don't know much about this issue. I'm looking into the output buffering solution. – Alan Navai Jul 13 '19 at 05:14
  • @AlanNavai You haven't supplied the operating system. You haven't described your runtime environment. Based on the limited information you've supplied, no one is going to be able to reproduce this problem. –  Jul 13 '19 at 05:25
  • @DavidCullen Yes, my bad. Anyways, the problem was the output buffering. – Alan Navai Jul 13 '19 at 05:41

2 Answers2

3

I believe this is because of output buffering. You can find the solution here: Disable output buffering

Jarett LeVan
  • 389
  • 1
  • 10
1
        for i in range(5):
            print(i)
            sleep(5)

do it like this, it is working in my side