我在 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()
不会调用 then 。我尝试放入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...
。我怎么能最好地处理这个,我觉得很愚蠢!
正如评论者所指出的,我使用的是 Python 2.5.4 Pys60