Skip to main content
 首页 » 编程设计

python之如何重试 urllib2.urlopen n 次

2025年05月04日14bonelee

我正在尝试实现一个装饰器以重试 urllib2.urlopen n 次。 我无法让装饰器工作。当我运行它时,出现以下错误: 追溯(最近一次通话): 文件“F:\retry\dec_class.py”,第 60 行,位于 x.getURLdata('127.0.0.1') TypeError: 'NoneType' 对象不可调用

谁能给我一只手吗?

import serial, urllib2, time 
from functools import wraps 
 
import xml.etree.cElementTree as ET 
from xml.etree.cElementTree import parse 
 
class Retry(object): 
 
    default_exceptions = (Exception) 
    def __init__(self, tries, exceptions=None, delay=0): 
 
        self.tries = tries 
        if exceptions is None: 
            exceptions = Retry.default_exceptions 
        self.exceptions = exceptions 
        self.delay = delay 
 
    def __call__(self, f): 
        def fn(*args, **kwargs): 
            tried = 0 
            exception = None 
 
            while tried <= self.tries: 
                try: 
                    return f(*args, **kwargs) 
                except self.exceptions, e: 
                    print "Retry, exception: "+str(e) 
                    time.sleep(self.delay) 
                tried += 1 
                exception = e 
                #if no success after tries, raise last exception 
                raise exception 
            return fn  
 
 
class getURL(object): 
 
    @Retry(2 ) 
    def getURLdata(self, IPaddress): 
 
        try: 
            f = urllib2.urlopen(''.join(['http://', IPaddress])) 
            f = ET.parse(f) 
 
            return f 
 
        except IOError, err: 
            print("L112 IOError is %s" %err) 
        except urllib2.URLError, err: 
            print("L114 urllib2.URLError is %s" %err) 
        except urllib2.HTTPError, err: 
            print("L116 urllib2.HTTPError is %s" %err) 
        except Exception, err : 
            print("L118 Exception is %s" %err) 
 
 
x = getURL() 
 
x.getURLdata('127.0.0.1') 

请您参考如下方法:

您的 __call__ 方法不返回 fn。相反,它隐式返回 None,因此 None 绑定(bind)到 getURLdata。