Search code examples
pythonpython-2.7for-loopcurlpycurl

How can I handle a pycurl.error - Timed out exception?


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:

for x in range (0, 161):

url = 'http://' + ips[x] + ':8080/version/'

storage = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEFUNCTION, storage.write)
#c.perform errors and once it errors, I would like to increment x to skip to the next IP.
c.perform()
c.close()
content = storage.getvalue()
print content

As above, c.perform errors and once it errors, I would like to increment x to skip to the next IP.

How would I be able to do this?

Thank you in advance.


Solution

  • perform raises pycurl.error exception upon failure. So you need to handle that in your code.

        try: 
            #do stuff
        except pycurl.error:
            continue