Ho seguente codice in uno script pythonchiusura dei file correttamente aperti con 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
Sono preoccupato, perché se io incontro un errore sul sf.read()
, quindi sf.clsoe()
non è chiamato. Ho provato a inserire sf.close()
in un blocco finally
, ma se c'è un'eccezione su urlopen()
, non c'è alcun file da chiudere e ho riscontrato un'eccezione nel blocco finally
!
Allora ho provato
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
ma questo ha sollevato un errore di sintassi non valida sulla linea with...
. Come posso gestire al meglio questo, mi sento stupido!
Come commentatori hanno fatto notare, sto usando PyS60 che è Python 2.5.4
L'istruzione "with" è disponibile solo in Python 2.6 o in 2.5 se si inserisce 'from __future__ import with_statement' nella parte superiore del file. Non ricordo bene quale versione Python PyS60 implementa ma potrebbe essere 2.5? –
è 2.5.4. l'importazione è un buon punto :) – Habbie