Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get out of a try/except inside a while? [Python]

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'
like image 717
Bruno 'Shady' Avatar asked Jul 07 '10 21:07

Bruno 'Shady'


2 Answers

You can use a custom exception and then catch it:

exit_condition = False

try:

    <some code ...>

    if exit_conditon is True:
        raise UnboundLocalError('My exit condition was met. Leaving try block')

    <some code ...>

except UnboundLocalError, e:
    print 'Here I got out of try with message %s' % e.message
    pass

except Exception, e:
    print 'Here is my initial exception'

finally:
    print 'Here I do finally only if I want to'
like image 37
dfostic Avatar answered Oct 04 '22 01:10

dfostic


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'
like image 84
petraszd Avatar answered Oct 04 '22 02:10

petraszd