2017-04-05 56 views
-1

我的PyCurl代码的目的是遍历IP地址数组,然后打印每个IP地址的响应主体。我该如何正确地继续出现潜在错误的for循环?

唯一的问题是,有些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循环,一旦出现错误?

回答

1

你应该做的就是把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 
+0

啊,这是总的感觉..非常感谢! – juiceb0xk