如何正确地继续带有潜在错误的 for 循环?

How do I properly continue a for loop with potential errors?

我的 PyCurl 代码的目的是遍历 IP 地址数组,然后打印每个 IP 地址的响应正文。

唯一的问题是,有些 IP 实际上是离线的,当 PyCurl 无法连接到 IP 时,它会出错并退出脚本。

我想让脚本做的是,如果 PyCurl 无法连接到 IP,请跳到下一个。这应该很简单,但我不确定我应该如何重写我的代码以允许此异常。

这是我的代码:

try:
    for x in range (0, 161):
        print ips[x]
        url = 'http://' + ips[x] + ':8080/config/version/'

        storage = StringIO()
        c = pycurl.Curl()
        c.setopt(c.URL, url)
        c.setopt(c.WRITEFUNCTION, storage.write)
        c.perform()
        c.close()
        content = storage.getvalue()
        print content

except pycurl.error:
    pass

我已经尝试 continue 但我收到错误 continue: not properly in loop

我如何编辑我的代码,以便在出错时我可以正确地继续 for 循环?

你应该做的是将 try...except 块放在你的循环中,这样如果错误被捕获,它将继续到下一个循环。

for x in range (0, 161):
    try:
        print ips[x]
        url = 'http://' + ips[x] + ':8080/config/version/'

        storage = StringIO()
        c = pycurl.Curl()
        c.setopt(c.URL, url)
        c.setopt(c.WRITEFUNCTION, storage.write)
        c.perform()
        c.close()
        content = storage.getvalue()
        print content

    except pycurl.error:
        continue