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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With