Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file descriptor is valid

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.

like image 736
Uyghur Lives Matter Avatar asked Aug 02 '11 17:08

Uyghur Lives Matter


1 Answers

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)
like image 74
Andrew Clark Avatar answered Sep 28 '22 10:09

Andrew Clark