出错时重试f = opener.open(url)

时间:2014-09-05 10:36:12

标签: python

我有一个python脚本按顺序进行2次调用,但是,有时我会收到错误:

socket.error: [Errno 54] Connection reset by peer

我希望每当它没有得到200响应时重试它。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用try和except子句:

while True:
   try:
       ... # make your conncetion here
       break
   except:
      print "soemthing went wrong, retrying"

答案 1 :(得分:1)

我不知道你的"揭幕战"是什么类型的对象。是,但我想你想要像

这样的东西
import urllib2

def open(url):
    while True:
        try:
            u= urllib2.urlopen(url)
        except urllib2.HTTPError, e:
            if e.getcode()==200: #no idea if it's even possible for a HTTPError to have code 200, but this way we're prepared for anything.
                raise
        except Exception:
            pass
        else:
            if u.getcode()==200:
                return u #on success, return
        #fallthrough: code!=200 or Exception has been raised, so try again.