如何处理pycurl.error - 超时异常?

时间:2017-04-04 06:34:06

标签: python python-2.7 for-loop curl pycurl

我的PyCurl代码的目的是迭代一组IP地址,然后打印每个IP地址的响应主体。

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

我希望脚本执行的操作是,如果PyCurl无法连接到IP,请跳到下一个。这应该很简单,但我不确定如何重新编写代码以允许此异常。

Heres'我的代码:

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

如上所述,c。执行错误,一旦出错,我想增加x跳到下一个IP。

我怎么能这样做?

提前谢谢。

1 个答案:

答案 0 :(得分:3)

perform在失败时引发pycurl.error例外。所以你需要在你的代码中处理它。

    try: 
        #do stuff
    except pycurl.error:
        continue
相关问题