Tinet
V2EX  ›  问与答

为什么这段代码老是出错,我已经无力了

  •  
  •   Tinet · Jun 26, 2013 · 4428 views
    This topic created in 4889 days ago, the information mentioned may be changed or developed.
    def GetPage(self,url):
    try:
    fp = urllib2.urlopen(url)
    result = fp.read()
    except Exception, e:
    self.logger.error(
    'url %s is unreachable. Exception %s %s' %
    (url, e.__class__.__name__, e))
    result=None
    fp.close()
    return result

    多个线程有可能同时执行这段代码,GetPage是一个对象里的方法
    有时会返回unboundlocalerror local variable fp referenced before assignment
    在线等高人赐教
    19 replies  •  1970-01-01 08:00:00 +08:00
    Tinet
    Tinet
    OP
    Jun 26, 2013
    1
    我去,不能缩进的吗
    Tinet
    Tinet
    OP
    Jun 26, 2013
    2
    告诉我为什么吧,新手Need Help
    leiz
    leiz
    Jun 26, 2013
    3
    应该是你第一行就出错,然后跳到exception,fp还没声明就使用,结果出错。
    把fp.close()改成 if not fp: fp.close()应该就可以了。
    leiz
    leiz
    Jun 26, 2013❤️1
    4
    写错,应该是if fp: fp.close()
    iptux
    iptux
    Jun 26, 2013❤️1
    5
    fp.close() 不是应该放在try里面的么
    Tinet
    Tinet
    OP
    Jun 26, 2013
    6
    @iptux
    @leiz except里只有它下面的四行,fp.close()是和try对齐的,我不知道这个怎么缩进,不好意思
    shiny
    shiny
    Jun 26, 2013❤️1
    7
    @Tinet 你可以贴 gist
    thedevil5032
    thedevil5032
    Jun 26, 2013❤️1
    8
    @Tinet 以后贴代码用 gist,很方便的。
    Tinet
    Tinet
    OP
    Jun 27, 2013
    9
    lululau
    lululau
    Jun 27, 2013❤️1
    15
    分别用这两个URL测试一下你就明白了

    'http://www.apple.com'
    'moc.elppa.www//:ptth'
    Perry
    Perry
    Jun 27, 2013
    16
    3楼即问题所在
    Tinet
    Tinet
    OP
    Jun 27, 2013
    17
    @lululau
    @Perry 是不是因为urllib2.urlopen(url)里面出错了,还没来得及给fp赋值就出异常跳到下面执行了
    Perry
    Perry
    Jun 27, 2013❤️1
    18
    @Tinet 一旦try里面出错,里面的赋值就不会延续到下面。相当于没有赋值
    Tinet
    Tinet
    OP
    Jun 27, 2013
    19
    @Perry 我刚看了一下文档,正如@lululau 所举的例子,当不能建立到目标url连接的时候,就会抛出一个IOError异常,学习了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   937 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 21:32 · PVG 05:32 · LAX 13:32 · JFK 16:32
    ♥ Do have faith in what you're doing.