我的 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 循环?
你应该做的是放置尝试...除了在循环内阻塞,因此如果捕获错误,它将继续到下一个循环。
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