V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Tinet
V2EX  ›  问与答

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

  •  
  •   Tinet · 2013-06-26 21:32:05 +08:00 · 3248 次点击
    这是一个创建于 3957 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    1970-01-01 08:00:00 +08:00
    Tinet
        1
    Tinet  
    OP
       2013-06-26 21:36:52 +08:00
    我去,不能缩进的吗
    Tinet
        2
    Tinet  
    OP
       2013-06-26 21:42:49 +08:00
    告诉我为什么吧,新手Need Help
    leiz
        3
    leiz  
       2013-06-26 21:47:24 +08:00
    应该是你第一行就出错,然后跳到exception,fp还没声明就使用,结果出错。
    把fp.close()改成 if not fp: fp.close()应该就可以了。
    leiz
        4
    leiz  
       2013-06-26 21:51:20 +08:00   ❤️ 1
    写错,应该是if fp: fp.close()
    iptux
        5
    iptux  
       2013-06-26 21:51:42 +08:00   ❤️ 1
    fp.close() 不是应该放在try里面的么
    Tinet
        6
    Tinet  
    OP
       2013-06-26 21:58:48 +08:00
    @iptux
    @leiz except里只有它下面的四行,fp.close()是和try对齐的,我不知道这个怎么缩进,不好意思
    shiny
        7
    shiny  
       2013-06-26 22:00:19 +08:00   ❤️ 1
    @Tinet 你可以贴 gist
    thedevil5032
        8
    thedevil5032  
       2013-06-26 22:01:04 +08:00   ❤️ 1
    @Tinet 以后贴代码用 gist,很方便的。
    Tinet
        9
    Tinet  
    OP
       2013-06-27 16:52:45 +08:00
    Tinet
        10
    Tinet  
    OP
       2013-06-27 17:01:40 +08:00
    Tinet
        11
    Tinet  
    OP
       2013-06-27 17:03:31 +08:00
    Tinet
        12
    Tinet  
    OP
       2013-06-27 17:07:12 +08:00
    Tinet
        13
    Tinet  
    OP
       2013-06-27 17:08:18 +08:00
    Tinet
        14
    Tinet  
    OP
       2013-06-27 17:12:05 +08:00
    lululau
        15
    lululau  
       2013-06-27 17:25:17 +08:00   ❤️ 1
    分别用这两个URL测试一下你就明白了

    'http://www.apple.com'
    'moc.elppa.www//:ptth'
    Perry
        16
    Perry  
       2013-06-27 17:25:28 +08:00
    3楼即问题所在
    Tinet
        17
    Tinet  
    OP
       2013-06-27 17:32:33 +08:00
    @lululau
    @Perry 是不是因为urllib2.urlopen(url)里面出错了,还没来得及给fp赋值就出异常跳到下面执行了
    Perry
        18
    Perry  
       2013-06-27 17:37:13 +08:00   ❤️ 1
    @Tinet 一旦try里面出错,里面的赋值就不会延续到下面。相当于没有赋值
    Tinet
        19
    Tinet  
    OP
       2013-06-27 17:43:59 +08:00
    @Perry 我刚看了一下文档,正如@lululau 所举的例子,当不能建立到目标url连接的时候,就会抛出一个IOError异常,学习了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3024 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:43 · PVG 16:43 · LAX 01:43 · JFK 04:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.