File Handling & TRY/EXCEPT

Steve Holden steve at holdenweb.com
Fri Aug 3 09:20:09 EDT 2007


Robert Rawlins - Think Blue wrote:
> Hello Guys,
> 
>  
> 
> I’m looking for some advice on how best to handle file read/write errors 
> with try/except as i’m a little vague on this, I have a small memory 
> leak in my app and I’m starting to think its generated by my log file 
> write. For an example of the function look below.
> 
>  
> 
>        def addAppLog(self, event):
>               try:
>                      logfile = open('/pblue/new/Logs/Application.csv','a')
>                      now = datetime.datetime.now()
>                      logstring = '%s,%s \n' % (event, str(now))
>                      logfile.write(logstring)
>               except:
>                      self.addAppLog(event)
> 
It seems somewhat perverse, when the logging code raises an exception, 
to recursively log - presumably the same exception will be raised again?

>               else:
> 
>                      logfile.close()
> 
Remember that in 2.5 you can use try ... except ... finally

> 
> Now I’m looking for some help to sort this out as I’m sure it’s pretty 
> untidy, I want to make it as air tight as possible. The basic concept 
> was that if it tries writing to the log file and it fails, then it needs 
> to reattempt it, right?
> 
Wrong. The one thing you can't log is a logging attempt error!
>  
> 
> What’s the best way to handle this to ensure that there are not any 
> memory leaks caused when the file is open() but not followed by a 
> close(). I’m running 2.4 and I know some of these newer versions don’t 
> need you to explicitly close() the file objects, but I would certainly 
> feel a lot better.
> 
>  
> 
> Any advice?
> 
This is just a quick on-the-fly look at what you did, I am sure you will 
receive other,  probably more helpful, comments.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list