2015-05-28 115 views
1

我有以下代碼,它使用urllib2發出http請求。代碼介於try /除了捕獲http錯誤之外。在某個時候,我得到一個urllib2.HttpError。我在捕捉它,並且我想在處理異常事件之前做上面的代碼(在catch之外)n次。以下代碼goto .label只是爲了演示我想要做什麼,但沒有找到如何去做。python:異常循環

recoveryTimes = 5 
try: 
      data = urllib.urlencode(values)  
      req = urllib2.Request(url, data) 
      label .request (this is where i want to jump after the exception) 
      urllib2.urlopen(req) 
      response = urllib2.urlopen(req)  
      the_page = response.read() 

except urllib2.HTTPError: 
       if (recoveryTimes > 0): 
        goto .request 
       else: 
        self.setUrllib2Proxy() 

進行彙總,如果一個http請求失敗,我想再試一次。只有在n次失敗之後,我纔想去else語句。

+0

你可以考慮使用[retying](https://pypi.python.org/pypi/retrying)模塊。 –

回答

0

您可以嘗試使用一個裝飾的代碼

import time 
import math 

def retry(tries, delay=1): 
    '''Retries a function or method until it returns True. 

    delay sets the initial delay in seconds. tries must be at least 0, and delay 
    greater than 0.''' 
    tries = math.floor(tries) 
    if tries < 0: 
     raise ValueError("tries must be 0 or greater") 
    if delay <= 0: 
     raise ValueError("delay must be greater than 0") 
    def deco_retry(f): 
     def f_retry(*args, **kwargs): 
      mtries = tries 
      rv = f(*args, **kwargs) 
      while mtries > 0: 
       if rv is True: 
        return True 
       mtries -= 1 
       time.sleep(delay) 
       rv = f(*args, **kwargs) 
      return False 
     return f_retry 
    return deco_retry 

重試yoour塊讓你的代碼的方法,他們必須返回真或假,並與前面的代碼裝飾它