pythonfdopen

Python get file path from a file descriptor int (as returned from os.open)


I am using fusepy and I need to convert a file descriptor back in to a file object so that I can obtain the original file path

From the fusepy examples, when a file is created, a file descriptor is returned - for example:

def open(self, path, flags):
    print("open:", path)
    return os.open(path, flags)

the returned result is an integer: <class 'int'> with the value of 4

in a separate function named write, I need to reverse the file descriptor back in to a file so that I can get the file path, so I tried this:

f = os.fdopen(fh)

When I check the type of f I get the following f is type: <class '_io.TextIOWrapper'>

Which is not quite what I was expecting but a quick dir(f) shows that it has a name property, I thought that's what I was looking for, except name is simply the number 4...

How can I get the original file path the descriptor points to?


Solution

  • Since this seems to satisfy the need, I'll post it as an answer for the time being. One could access underlying objects through f.buffer and f.buffer.raw (not the surprise mentioned in question depends a bit on Python version used, in v2 this looked different), but that still won't help accessing the filename used top open the file. Note: this could have just as well taken place in a calling process and a descriptor could have been inherited by the python process.

    Not sure if there is a nicer and more portable way, but one can query OS and on U*X like system a readily available way would be to reference procfs structure, namely for the above example:

    os.readlink(f"/proc/self/fd/{fh}")
    

    Still not an entirely trivial question. Descriptor may still be open and used, while the underlying file(name; filesystem reference) has already been deleted.