fea*_*urs 7 python exception-handling urllib2 pys60
我在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
Run Code Online (Sandbox Code Playgroud)
我很担心,因为如果我遇到错误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
Run Code Online (Sandbox Code Playgroud)
但这会with...在行上引发无效的语法错误.我怎么能最好地处理这个问题,我觉得很蠢!
正如评论者指出的那样,我使用的是Pys60,它是python 2.5.4
Dan*_*iel 17
我会使用contextlib.closing(与旧的Python版本的__future__ import with_statement结合使用):
from contextlib import closing
with closing(urllib2.urlopen('http://blah')) as sf:
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
Run Code Online (Sandbox Code Playgroud)
或者,如果您想避免使用with语句:
try:
sf = None
sf = urllib2.urlopen('http://blah')
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
finally:
if sf:
sf.close()
Run Code Online (Sandbox Code Playgroud)
虽然不那么优雅.
为什么不尝试关闭sf,如果它不存在则传递?
import urllib2
try:
search_query = 'http://blah'
sf = urllib2.urlopen(search_query)
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
except urllib2.URLError, err:
print(err.reason)
finally:
try:
sf.close()
except NameError:
pass
Run Code Online (Sandbox Code Playgroud)