如何重试urllib2.urlopen n次

2024-09-30 01:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现一个decorator来重试urllib2.urlopen n次。 我找不到装修工。当我运行它时,我得到以下错误: 回溯(最近一次呼叫): 文件“F:\retry\dec_类.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')

Tags: importselfisdefexceptionurllib2exceptionserr

热门问题