-1

The purpose of my PyCurl code is to iterate through an array of IP addresses and then print the response body's of each IP Address.

The only problem with this, is that some IP's are actually offline, and when PyCurl cannot connect to the IP, it errors and exits the script.

What I want the script to do, is if PyCurl cannot connect to the IP, skip to the next one. This should be simple, but I'm not sure how I should re-write my code to allow this exception.

Heres' my code:

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

I have tried continue but I get the error continue: not properly in loop.

How can I edit my code so that I can properly continue the for loop once it errors?

juiceb0xk
  • 949
  • 3
  • 19
  • 46

1 Answers1

1

What you should do is to place the try...except block inside your loop so it will continue to the next loop if the error is caught.

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
Taku
  • 31,927
  • 11
  • 74
  • 85