File Handling & TRY/EXCEPT

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Aug 5 12:29:16 CEST 2007


En Fri, 03 Aug 2007 10:38:17 -0300, Robert Rawlins - Think Blue  
<robert.rawlins at thinkbluemedia.co.uk> escribió:

> Thanks for your ideas guys,
>
> I'm unfortunately tied to 2.4 so don't have the full try except status,  
> but
> I'm now working with the following code:
>
> 	def addApp(self, event):
> 		try:
> 			logfile =
> open('/pblue/new/Logs/Application.csv','a')
>
> 			now = datetime.datetime.now()
> 			logstring = '%s,%s \n' % (event, str(now))
> 			
> 			try:				
> 				logfile.write(logstring)
> 			finally:
> 				logfile.close()
> 		except:
> 			self.addApp(event)
>
> I'm trying to slowly debug my app and get rid of all the memory leaks,  
> but
> its pain staking work, any help you can offer on that stuff would be a  
> god
> send, I'm a little reluctant about posting all my app code on the lists  
> as
> I'd like to keep some of it private.
>
> How does that new version look? A little tidier?

If the logging error is rather permanent (disk full) or a programming  
error (e.g. you forget to import datetime) this will cause an infinite  
recursion. Don't try to log again, at least not the same way.
The version below writes to the console when a logging error happens. And  
note the reordered open/try/finally: you want to ensure that after a call  
to open, no matter what happens, the file will be closed.

def addApp(self, event):
     try:
         now = datetime.datetime.now()
         logstring = '%s,%s \n' % (event, str(now))
         logfile = open('/pblue/new/Logs/Application.csv','a')
         try:
             logfile.write(logstring)
         finally:
             logfile.close()
     except:
         print >>sys.stderr, "%s: %s while attempting to log event '%s'" % (
             sys.exc_info()[0], sys.exc_info()[1], event)


-- 
Gabriel Genellina




More information about the Python-list mailing list