我有一個python腳本關閉文件與urllib2.urlopen正常打開()
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這是蟒蛇2.5.4
「with」語句僅在Python 2.6中可用,如果將'from __future__ import with_statement'放在文件的頂部,則該語句只能在2.5中使用。我不太清楚Python版本PyS60實現的是什麼,但它可能是2.5? – 2010-10-07 10:47:28
它是2.5.4。進口是一個好點:) – Habbie 2010-10-07 10:48:56