Low level file descriptors and high-level Python files

random832 at fastmail.us random832 at fastmail.us
Tue Sep 1 11:56:04 EDT 2015


On Tue, Sep 1, 2015, at 10:57, Steven D'Aprano wrote:
> Q1:  In this example, I know that I opened the fd in write mode, because
> I
> did it myself. But since I'm not actually opening it, how do I know what
> mode to use in the call to fdopen? Is there something I can call to find
> out what mode a file descriptor has been opened with?

In principle, you can find out with fcntl.

In practice, don't you already know what kind of processing you intend
to do with the file? If your "processing" involves writing, just try
writing to it, and if it doesn't work then it's the caller's fault for
passing in a read-only file handle.

> Now let's suppose I solve that problem, process the file_obj, and close
> it:
> 
> file_obj.close()
> 
> Q2:  Do I still have to close the file descriptor with os.close(fd)? 
> (I think not.)

You do not.

> Q3:  I could probably answer Q2 myself if I knew how to check whether a
> fd
> was open or not. With a file object, I can inspect file_obj.closed and it
> will tell me whether the file is open or not. Is there an equivalent for
> file descriptors?

Well, if you try to call os.close, or any other operation for that
matter, it will raise an OSError with errno=EBADF.

Note that if the file _has_ been closed it may be reused by the next
open call, so it's best not to use this test method in production code.



More information about the Python-list mailing list