0

I'm making a fibonacci sequence. Everytime I deal with Console (on Windows), it runs too fast and suddenly exits for itself.

So I use Time.sleep() to look what's going on. Here is the source:

    def fibo():
      pv1,pv2 = 0,1
      while True:
        yield pv2
        pv1,pv2=pv2,pv1+pv2
    import time
    f=fibo()
    for result in f:
      print(result,end=' ')
      time.sleep(0.5)

I expected "1 1 2 3 ..." per 0.5 secs but it never works! Without the sleeping method, it runs fine. I think there's something but I'm too ignorant to know why.

CRM
  • 4,569
  • 4
  • 27
  • 33
from __future__
  • 305
  • 2
  • 6
  • 1
    What do you mean by "never works"? What *does* it do? – Eli Bendersky May 30 '12 at 02:40
  • on my computer, nothing happens. the console screen makes nothing, just stand alone – from __future__ May 30 '12 at 02:42
  • I will suggest that you work from a command line terminal, and call youyr program from there - this way you may worry about your code, and not with artificial constructs needed for a development unfirendly environment (i.e. your calls to time.sleep). Keep in miund that alkl Python development itself is made by people who use the command line. – jsbueno May 30 '12 at 02:45

1 Answers1

2

By default, when the standard output goes to a terminal, output is line-buffered. You can make your code work as expected by manually flushing standard output. This is how you'd flush standard output:

import sys  # probably near the top of the file
sys.stdout.flush()  # after printing
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • but I still don't know what's diffence with or without sleep in buffer area...would you please introduce me any doc or link? I'll appreciate! – from __future__ May 30 '12 at 02:46
  • 1
    @stackneveroverflow: There isn't really any difference. With the sleep, the problem is more obvious. Without the sleep, the problem is less visible. The standard output is flushed when the program exits, so that's why you saw (briefly) the output of that program. In reality, even without the explicit flushing, it's flushing at script finish even with the sleep. It's just difficult to see because the interval is so short. Anyway, [this is a somewhat-related question](http://stackoverflow.com/q/107705). The real answer is §7.1.3 ¶3 of the C99 standard. – icktoofay May 30 '12 at 02:58