views:

60

answers:

2

I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying until connected.

So I just added the following code in the event, but found it didn't work. Also the whole program has to be closed in a forced way. Here's my code:

import urllib2
import time

InternetNotOn = True

while InternetNotOn:
    try:
        urllib2.urlopen("http://google.com")
        InternetNotOn = False
        print "Everyting is fine!"
    except urllib2.URLError, e:
        print "Error!"
        time.sleep(10)

What could the problem be?

+3  A: 

When you have an event based program, the overall flow of the program is this:

while the-program-is-running:
    wait-for-an-event
    service-the-event
exit

Now, lets see what happens when service-the-event calls something with a (potentially) infinite loop:

while the-program-is-running:
    wait-for-an-event
    while the-internet-is-on:
        do-something
exit

Do you see the problem? In the worse case your program may never call wait-for-an-event again because your loop is running.

Remember: the event loop is already an infinite loop, you don't need to add another infinite loop inside of it. Instead, take advantage of the existing loop. You can use wx.CallAfter or wx.CallLater to call a method which will cause your function to be called at the next iteration of the event loop.

Then, within your function you call wx.CallAfter or wx.CallLater again to cause it to again be called on the next iteration of the event loop.

Bryan Oakley
Thanks a lot, man!
Shane
See also http://wiki.wxpython.org/LongRunningTasks
Mike Driscoll
A: 

Instead of time.sleep(10) you can call wxApp::Yield and time.sleep(1) ten times.

Beware of reentrancy problems (e.g. pressing the start button again.). The start button could be dimmed while in the event handler.

But Bryan Oakley's solution is probably the better way.

Peter Mortensen