开发者

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.


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)


How about trying to os.write to fd=3 once at the start (inside a try-except block), and change all subsequent behaviour based on the success of that?

This way you won't have to wrap every call in try-except. Of course, this will break down if fd=3 stops being valid in the middle of your problem (e.g. if it's a pipe that gets closed from the other end).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜