Get file object from file number

Let's say I have a list of open files (actually, file numbers):

import resource import fcntl def get_open_fds(): fds = [] soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) for fd in range(3, soft): try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fds.append(fd) return fds 

Now I would like to get the names of these files. How can i do this?

EDIT

Just for clarification, for those who do this: fd is an integer. This is NOT a pointer file. Sorry for confusing the name, but the code is self-explanatory.

EDIT2

I hit it, I think, because my choice of fd means the file number. I just checked the documentation :

All functions in this module accept the file descriptor fd as the first argument. This can be an integer file descriptor, for example, returned by sys.stdin.fileno (), or a file object, such as sys.stdin, that provides fileno (), which returns a genuine file descriptor.

So fd really an integer. It can also be a file object, but in the general case, fd does not matter .name .

+7
source share
2 answers

Like this answer :

 for fd in get_open_fds(): print fd, os.readlink('/proc/self/fd/%d' % fd) 
+6
source

I was in the same boat. What I ended up with is writing my own open , which keeps track of all open files. Then in the Python source file, the first thing that happens is the built-in open , which is replaced by mine, and then I can request it for open files. It looks like this:

 class Open(object): builtin_open = open _cache = {} @classmethod def __call__(cls, name, *args): file = cls.builtin_open(name, *args) cls._cache[name] = file return file @classmethod def active(cls, name): cls.open_files() try: return cls._cache[name] except KeyError: raise ValueError('%s has been closed' % name) @classmethod def open_files(cls): closed = [] for name, file in cls._cache.items(): if file.closed: closed.append(name) for name in closed: cls._cache.pop(name) return cls._cache.items() import __builtin__ __builtin__.open = Open() 

and then...

 daemon.files_preserve = [open.active('/dev/urandom')] 
+2
source

All Articles