Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file object from file number

Tags:

python

file

Let's say I have a list of the opened files (actually, of the 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 those files. How can I do this?

EDIT

Just to clarify, for those downvoting this: fd is an integer. It is NOT a filedescriptor. Sorry for confusing you with the name, but the code is self-explanatory.

EDIT2

I am getting flamed about this, I think because of my choice of fd to mean file number. I just checked the documentation:

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

So fd is indeed an integer. It can also be a file object but, in the general case, fd has not .name.

like image 505
blueFast Avatar asked Nov 29 '12 09:11

blueFast


People also ask

How do you get the name of a file from a file object?

The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.

What are file objects in Python?

A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is raised.


1 Answers

As per this answer:

for fd in get_open_fds():
    print fd, os.readlink('/proc/self/fd/%d' % fd)
like image 125
georg Avatar answered Nov 14 '22 22:11

georg