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

前端 未结 4 737
野趣味
野趣味 2021-02-14 16:12

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.urlo         


        
相关标签:
4条回答
  • 2021-02-14 16:52

    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'
    
    0 讨论(0)
  • 2021-02-14 16:55

    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'
    
    0 讨论(0)
  • 2021-02-14 16:56

    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.

    0 讨论(0)
  • 2021-02-14 17:11

    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.

    0 讨论(0)
提交回复
热议问题