0
import urllib2
import webbrowser
import time
import sys

URL = "http://nonexisting"

while True:
    try:
        website = urllib2.urlopen(URL, timeout=1)

        if website:
            webbrowser.open_new(URL)
            break

    except KeyboardInterrupt:
        break

    except:
        sys.stdout.write('.')
        time.sleep(1)

I expect this code to write out a dot every second, but instead nothing is happening and when I press CTRL-C I get this output:

^C..........Traceback (most recent call last):
  File "stackoverflow_question.py", line 21, in <module>
    time.sleep(1)
KeyboardInterrupt

So every dot appear after the interrupt. Why is that ? How can I reach the expected result ? I tried with print statement either with the same result. On OS X and linux too.

kissgyorgy
  • 2,947
  • 2
  • 32
  • 54

2 Answers2

3

You did not flush the buffer, so the output did not actually happen; it's stored somewhere in limbo.

After you interrupt, the buffer gets flushed.

See these links for more information:

Disable output buffering

How to flush output of Python print?

Also, quote from mgilson from the comment:

this code will spend most of it's time in time.sleep. During that interval, the KeyboardInterrupt won't get caught.

Community
  • 1
  • 1
zw324
  • 26,764
  • 16
  • 85
  • 118
0

Did you try using print istead of sys.stdout.write?

print '.'
Dory Zidon
  • 10,497
  • 2
  • 25
  • 39