tags:

views:

94

answers:

3

I'm trying this simple code, but the damn break doesn't work... what is wrong?

while True:
    for proxy in proxylist:
        try:
            h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
            print 'worked %s' % proxy
            break
        except:
            print 'error %s' % proxy
print 'done'

It's supposed to leave the while when the connection work, and go back and try another proxy if it didn't

ok, here is what I'm doing

I'm trying to check a website and if it changed, it has to break out of the while to continue to the rest of the script, but when the proxy doesn't connect, I get error from the variable, as it's null, so what I want is this for work as loop to try a proxy, and if it work, continue the script, and the end of the script, go back and try the next proxy, and if the next doesn't work, it will be back to the beginning to try the third proxy, and so on....

I'm trying something like this

while True:
    for proxy in proxylist:
        try:
            h = urllib.urlopen(website, proxies = {'http': proxy})
        except:
            print 'error'
        check_content = h.readlines()
        h.close()
        if check_before != '' and check_before != check_content:
            break
        check_before = check_content
        print 'everything the same'
print 'changed'
+5  A: 

You just break out of for loop -- not while loop:

running = True
while running:
    for proxy in proxylist:
        try:
            h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
            print 'worked %s' % proxy
            running = False
        except:
            print 'error %s' % proxy
print 'done'
petraszd
You may also want to keep the break after setting running to False, if it doesn't make sense to continue lopping through proxies.
mrooney
I see no reason to have while at all -- I just left it in my code example, because I think it is simplified version of what author actually tries to achieve. The simplest solution would be just to remove while loop.
petraszd
The while loop lets the script try the same proxies again, in hopes that maybe one of them started working now. Instead of the while loop you could use for proxy in itertools.cycle(proxylist) and then a simple `break` would suffice with no need of extra control variables.
Marius Gedminas
+2  A: 

You break out of the for loop only, so you never leave the while loop and restart iterating over the proxylist over and over again. Just omit the surrounding while loop, I actually don't understand why you enclosed the code in a while True in the first place.

jellybean
+1  A: 

break is breaking the innermost loop, which is the for loop in your case. To break from more than one loop you have few options:

  1. Introduce a condition
  2. Create a sub and use return

but in your case you actually don't need the outer while loop at all. Just remove it.

unbeli