如何在while中退出try/except? [Python]

21 投票
4 回答
126632 浏览
提问于 2025-04-16 00:58

我在尝试这段简单的代码,但这个该死的break(跳出循环的命令)不管用……到底哪里出了问题?

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'

我希望当连接成功时能跳出while循环,如果连接失败就去尝试另一个代理。

好吧,我来讲讲我在做什么。

我想检查一个网站,如果网站内容有变化,就需要跳出while循环,继续执行后面的代码。但是当代理连接不上时,我会收到一个错误,因为那个变量是空的。所以我想要的是这个循环能尝试一个代理,如果成功就继续执行脚本,脚本结束后再回去尝试下一个代理。如果下一个代理也不行,就再回到最开始去尝试第三个代理,依此类推……

我在尝试类似这样的代码:

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 个回答

4

在你的例子中,break 是用来结束最里面的循环,也就是那个 for 循环。如果你想要同时结束多个循环,有几种方法可以做到:

  1. 设置一个条件
  2. 创建一个子程序,然后使用 return 来返回

不过在你的情况里,其实根本不需要外面的 while 循环。直接把它删掉就可以了。

6

你可以使用自定义的异常,然后捕获它:

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'
17

你只是跳出了 for 循环,而不是 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'

撰写回答