正在关闭用urllib2.urlopen()正确打开的文件

2024-09-27 07:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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


Tags: closereadsearchexceptionsfurllib2queryurlopen
3条回答

我将使用contextlib.closing(与旧Python版本的from uuu future uuu import with u语句结合使用):

from contextlib import closing

with closing(urllib2.urlopen('http://blah')) as sf:
    search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())

或者,如果要避免with语句:

try:
    sf = None
    sf = urllib2.urlopen('http://blah')
    search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
finally:
    if sf:
        sf.close()

不过不太优雅。

finally:
    if sf: sf.close()

为什么不尝试关闭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

相关问题 更多 >

    热门问题