views:

100

answers:

3

Possible Duplicate:
check what files are open in Python

Hello,

Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment.

I am interested in theis function as I would like to safely handle any files that are open when a fatal error is raised, i.e. close file handles and replace potentially corrupted files with the original files.

I have the handling working but without knowing what file handles are open, I am unable to implement this idea.

As an aside, when a file handle is initialised, can this be inherited by another imported method?

Thank you

A: 

lsof, /proc/pid/fd/

dimba
+2  A: 
katrielalex
A: 

If you're using python 2.5+ you can use the with keyword (though 2.5 needs `from future import with_statement)

with open('filename.txt', 'r') as f:
    #do stuff here
    pass
#here f has been closed and disposed properly - even with raised exceptions

I don't know what kind of catastrophic failure needs to bork the with statement, but I assume it's a really bad one. On WinXP, my quick unscientific test:

import time
with open('test.txt', 'w') as f:
   f.write('testing\n')
   while True:
       time.sleep(1)

and then killing the process with Windows Task Manager still wrote the data to file.

Wayne Werner