How to get out of attempt / outside inside? [Python]

I try this simple code, but the damn break does not work ... what's 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 should leave the time when the connection is working, and go back and try another proxy if it doesn’t

ok that's what i do

I am trying to check the website, and if it has changed, it should exit this time to continue the rest of the script, but when the proxy does not connect, I get an error from the variable, since this is a null value, so I want this worked like a loop to try the proxy server, and if it works, continue the script and end the script, go back and try the next proxy server, and if the next one does not work, it will go back to the beginning to try the third proxy, etc. ...

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' 
+4
source share
4 answers

You just exit the for loop - not while :

 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' 
+10
source

You exit the for loop, so you never leave the while loop and repeat over and over again with proxylist . Just omit the surrounding while loop, I really don't understand why you entered the code in while True in the first place.

+3
source

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' 
+2
source

break breaks the innermost loop, which is the for loop in your case. To exit more than one cycle, you have several options:

  • Enter condition
  • Create a sub and use return

but in your case you don’t need the external while . Just delete it.

+1
source

Source: https://habr.com/ru/post/1315003/


All Articles