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

1

6

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?

Antisepsis answered 3/10, 2019 at 11:38 Comment(2)
You could access the underlying objects through f.buffer and f.buffer.raw, but you still wouldn't get to the name. Not very portable, but at least if on Linux and (I presume at least some) other U*X like systems, a way around could be to ask OS directly, e.g. through procfs structures: os.readlink(f"/proc/self/fd/{fh}") in your example.Fixed
@OndrejK. that'll do nicely - thank you; I didn't realise /proc/self was a thing either, so +1 for that too (I was at this point prior to your answer os.readlink("/proc/"+str(pid)+"/fd/"+str(fh)) but your example is much cleaner)Antisepsis
F
7

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.

Fixed answered 3/10, 2019 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.