我在python脚本中有以下代码
try:
# send the query request
sf = urllib2.urlopen(search_query)
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
sf.close()
except Exception, err:
print("Couldn't get programme information.")
print(str(err))
return
我很担心,因为如果在sf.read()
上遇到错误,那么sf.clsoe()
不会被调用。
我试着把sf.close()
放在finally
块中,但是如果urlopen()
上有异常,那么就没有要关闭的文件,我在finally
块中遇到异常!
所以我试着
try:
with urllib2.urlopen(search_query) as sf:
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
except Exception, err:
print("Couldn't get programme information.")
print(str(err))
return
但这在with...
行上引发了无效语法错误。
我怎么能最好地处理这个,我觉得自己很蠢!
正如评论人士所指出的,我使用的Pys60是Python2.5.4
我将使用contextlib.closing(与旧Python版本的from uuu future uuu import with u语句结合使用):
或者,如果要避免with语句:
不过不太优雅。
为什么不尝试关闭
sf
,如果不存在则传递?相关问题 更多 >
编程相关推荐