Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all currently open file handles? [duplicate]

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

like image 349
Thorsley Avatar asked Jul 30 '10 10:07

Thorsley


2 Answers

lsof, /proc/pid/fd/

like image 185
dimba Avatar answered Sep 21 '22 07:09

dimba


The nice way of doing this would be to modify your code to keep track of when it opens a file:

def log_open( *args, **kwargs ):
    print( "Opening a file..." )
    print( *args, **kwargs )
    return open( *args, **kwargs )

Then, use log_open instead of open to open files. You could even do something more hacky, like modifying the File class to log itself. That's covered in the linked question above.

There's probably a disgusting, filthy hack involving the garbage collector or looking in __dict__ or something, but you don't want to do that unless you absolutely really truly seriously must.

like image 25
Katriel Avatar answered Sep 17 '22 07:09

Katriel