未绑定的局部变量 Python 3.2



这个错误是随机弹出的,我很确定这是因为在 return 语句调用它之前没有初始化 infoGotten 变量。让我感到困惑的部分是它是如何到达代码的那部分以首先产生该错误。希望有人可以向我解释为什么会这样,因为我还没有弄清楚。我猜这是因为 try/except 语句,但我做了一些搜索并在手册中检查了 7.4,看起来(无论如何对我来说)我正在做不正确的事情。

breakLoop = 0
def get_item_info(linkParameters):
    global breakLoop
    nheaders = {'User-Agent' : 'Firefox/15.0.1'}
    purl = 'http://example.com/something.php'
    pd = linkParameters
    nreq = urllib.request.Request(purl, pd, nheaders)
    if breakLoop >= 4:
        return 'Request timed out {} times'.format(breakLoop)
    try:
        nresponse = urllib.request.urlopen(nreq)
    except urllib.error.URLError:
        breakLoop += 1
        get_item_info(pd)
    except urllib.error.HTTPError:
        breakLoop += 1
        get_item_info(pd)        
    else:
        infoGotten = nresponse.read()
    return infoGotten

谢谢!

您需要返回递归调用的结果,因此它应该return get_item_info(pd)except 子句中(我在下面进行了组合):

breakLoop = 0
def get_item_info(linkParameters):
    nheaders = {'User-Agent' : 'Firefox/15.0.1'}
    purl = 'http://example.com/something.php'
    pd = linkParameters
    nreq = urllib.request.Request(purl, pd, nheaders)
    if breakLoop >= 4:
        return 'Request timed out {} times'.format(breakLoop)
    try:
        nresponse = urllib.request.urlopen(nreq)
    except (urllib.error.URLError, urllib.error.HTTPError):
        breakLoop += 1
        return get_item_info(pd)
    else:   
        return nresponse.read()

递归似乎是一种奇怪的重试方式,为什么不使用循环呢? 以下似乎更清楚:

def get_item_info(linkParameters):
    nheaders = {'User-Agent' : 'Firefox/15.0.1'}
    purl = 'http://example.com/something.php'
    pd = linkParameters
    for i in range(5):
        nreq = urllib.request.Request(purl, pd, nheaders)
        try:
            nresponse = urllib.request.urlopen(nreq)
            return nresponse.read()
        except (urllib.error.URLError, urllib.error.HTTPError):
            pass
    return 'Request timed out 4 times'

最新更新