Best way to test if a file descriptor is valid?

Peter Hansen peter at engcorp.com
Mon Feb 24 22:34:06 EST 2003


Noah wrote:
> 
> I have a method that is passed an open file descriptor.
> This file descriptor may have been opened from a file or
> from a serial device or whatever. Is there a good way to test if
> the file descriptor is valid and available for read/write?
> 
> Currently I'm doing this:
>     try:
>         os.fstat(command)
>     except OSError:
>         raise Exception, 'Command is not a valid file descriptor.'
> 
> Which is OK I guess... Is there another way?

Have you considered just catching the exception that would be
generated if you just assumed it was valid, went ahead with
the proposed read/write operation, and it turned out it wasn't
"valid" (which could mean several things)?

By doing this, you are sure to properly handle not only the 
cases you probably envision, but any other errors that might
occur as a result.

If all you do is attempt a check ahead of time, then you still
need to catch the eventual exception(s) that might occur, so
why not save yourself the extra effort and just do the latter?

(Of course, there may be cases where it would be unsafe even
to attempt the operation on certain descriptors.  Maybe you
have one such instance?)

-Peter




More information about the Python-list mailing list