如何在一段时间内尝试/除外?[蟒蛇]

Bru*_*dy' 7 python while-loop

我正在尝试这个简单的代码,但该死的休息不起作用......出了什么问题?

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'
Run Code Online (Sandbox Code Playgroud)

它应该在连接工作时离开,并返回并尝试另一个代理,如果它没有

好的,这就是我正在做的事情

我正在尝试检查一个网站,如果它发生了变化,它必须突破一段时间才能继续执行其余的脚本,但是当代理没有连接时,我从变量中得到错误,因为它是null,所以我想要的是工作作为循环来尝试代理,如果它工作,继续脚本,脚本结束,返回并尝试下一个代理,如果下一个不起作用,它将回到开始尝试第三个代理,依此类推......

我正在尝试这样的事情

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'
Run Code Online (Sandbox Code Playgroud)

pet*_*szd 12

你刚刚摆脱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'
Run Code Online (Sandbox Code Playgroud)

  • 如果没有意义继续通过代理,你可能还想在设置运行到False之后保持中断. (8认同)

dfo*_*tic 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'
Run Code Online (Sandbox Code Playgroud)

  • @ChristopherPisz 没有。在Python中,异常通常是推荐的做事方式 (3认同)