V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Tinet
V2EX  ›  问与答

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

  •  
  •   Tinet · Jun 26, 2013 · 3919 views
    This topic created in 4691 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
        1
    Tinet  
    OP
       Jun 26, 2013
    我去,不能缩进的吗
    Tinet
        2
    Tinet  
    OP
       Jun 26, 2013
    告诉我为什么吧,新手Need Help
    leiz
        3
    leiz  
       Jun 26, 2013
    应该是你第一行就出错,然后跳到exception,fp还没声明就使用,结果出错。
    把fp.close()改成 if not fp: fp.close()应该就可以了。
    leiz
        4
    leiz  
       Jun 26, 2013   ❤️ 1
    写错,应该是if fp: fp.close()
    iptux
        5
    iptux  
       Jun 26, 2013   ❤️ 1
    fp.close() 不是应该放在try里面的么
    Tinet
        6
    Tinet  
    OP
       Jun 26, 2013
    @iptux
    @leiz except里只有它下面的四行,fp.close()是和try对齐的,我不知道这个怎么缩进,不好意思
    shiny
        7
    shiny  
    PRO
       Jun 26, 2013   ❤️ 1
    @Tinet 你可以贴 gist
    thedevil5032
        8
    thedevil5032  
       Jun 26, 2013   ❤️ 1
    @Tinet 以后贴代码用 gist,很方便的。
    Tinet
        9
    Tinet  
    OP
       Jun 27, 2013
    Tinet
        10
    Tinet  
    OP
       Jun 27, 2013
    Tinet
        11
    Tinet  
    OP
       Jun 27, 2013
    Tinet
        12
    Tinet  
    OP
       Jun 27, 2013
    Tinet
        13
    Tinet  
    OP
       Jun 27, 2013
    Tinet
        14
    Tinet  
    OP
       Jun 27, 2013
    lululau
        15
    lululau  
       Jun 27, 2013   ❤️ 1
    分别用这两个URL测试一下你就明白了

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