Check if file descriptor is valid

All Workers Are Essential picture All Workers Are Essential · Aug 2, 2011 · Viewed 8.3k times · Source

How do I check to see if a given file descriptor is valid? I want to write to fd=3 if it's available; otherwise, I want to write to stdout. I'm aware that I could wrap every os.write call with try-except statement, but I would like to know ahead of time if fd=3 is writable or not.

Answer

Andrew Clark picture Andrew Clark · Aug 2, 2011

You could use os.fstat to determine if the file descriptor is valid before each write, but you will need to wrap it in a try/except anyway because invalid file descriptors will raise an OSError. You are probably better off just creating your own write function with a try/except.

def write(data, fd=3):
    try:
        os.write(fd, data)
    except OSError:
        sys.stdout.write(data)