【发布时间】:2010-10-07 10:31:44
【问题描述】:
我在 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,它是 python 2.5.4
【问题讨论】:
-
"with" 语句仅在 Python 2.6 中可用,如果您将
from __future__ import with_statement放在文件顶部,则在 2.5 中可用。我不太记得 PyS60 实现了什么 Python 版本,但它可能是 2.5? -
它是 2.5.4。导入是一个好点:)
标签: python exception-handling urllib2 pys60