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

2013 年 6 月 26 日
 Tinet
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
在线等高人赐教
3832 次点击
所在节点    问与答
19 条回复
Tinet
2013 年 6 月 26 日
我去,不能缩进的吗
Tinet
2013 年 6 月 26 日
告诉我为什么吧,新手Need Help
leiz
2013 年 6 月 26 日
应该是你第一行就出错,然后跳到exception,fp还没声明就使用,结果出错。
把fp.close()改成 if not fp: fp.close()应该就可以了。
leiz
2013 年 6 月 26 日
写错,应该是if fp: fp.close()
iptux
2013 年 6 月 26 日
fp.close() 不是应该放在try里面的么
Tinet
2013 年 6 月 26 日
@iptux
@leiz except里只有它下面的四行,fp.close()是和try对齐的,我不知道这个怎么缩进,不好意思
shiny
2013 年 6 月 26 日
@Tinet 你可以贴 gist
thedevil5032
2013 年 6 月 26 日
@Tinet 以后贴代码用 gist,很方便的。
Tinet
2013 年 6 月 27 日
Tinet
2013 年 6 月 27 日
Tinet
2013 年 6 月 27 日
Tinet
2013 年 6 月 27 日
Tinet
2013 年 6 月 27 日
Tinet
2013 年 6 月 27 日
lululau
2013 年 6 月 27 日
分别用这两个URL测试一下你就明白了

'http://www.apple.com'
'moc.elppa.www//:ptth'
Perry
2013 年 6 月 27 日
3楼即问题所在
Tinet
2013 年 6 月 27 日
@lululau
@Perry 是不是因为urllib2.urlopen(url)里面出错了,还没来得及给fp赋值就出异常跳到下面执行了
Perry
2013 年 6 月 27 日
@Tinet 一旦try里面出错,里面的赋值就不会延续到下面。相当于没有赋值
Tinet
2013 年 6 月 27 日
@Perry 我刚看了一下文档,正如@lululau 所举的例子,当不能建立到目标url连接的时候,就会抛出一个IOError异常,学习了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/73733

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX