[Tutor] "Print" behaviour inside a loop?

Simon Gerber nequeo at gmail.com
Sun Jun 12 01:42:27 CEST 2005


Hullo,

Firstly, thanks to everyone who helped me find my own IP address. That 
was a big help. That bit is working now, and working very nicely. I am 
now stuck on something purely aesthetic - printing a few dots across the 
screen to provide a bit of feedback while the VPN tunnel is being 
established.

def vpn_connect(choice):
    import time
    ip_addr = ""
    tries = 0
    retries = 10
    print "Connecting to %s" % (choice),
    os.system("pon %s" % (choice))
    while ip_addr == "" and tries < retries:
        print "...",                 # This is the line causing problems
        time.sleep(0.5)
        ip_addr = get_addr()
        if ip_addr != '':
              #create the route!         
              pass
        else:
              tries += 1
    sys.exit()

It works. The problem is, nothing is displayed on screen until after the 
connection occurs - at which point we see:

"Connecting to Prodigi ... ... ... ... ... ... ... "

If I remove the comma at the end of the marked line, the ellipses  print 
every .5 seconds as desired, except they print down the screen of course!

After googling around a little, I found a post that seemed to say  
Python won't draw the results of 'print' statements until it hits a 
newline. I tried using sys.stout.write('...'), but had the same problem 
there, too. I've also found a few progress bar classes around the web, 
but I not exactly want a progress bar. I just want to print '...' every 
few seconds until connected.

Any hints? I looked up the python reference manual, but couldn't find 
any way to force print statements to draw. Should I be looking into 
threads, perhaps?

Regards,




More information about the Tutor mailing list