Source : Python gotcha
Don’t ever do this unless it’s really what you want:
import os def some_func(fd): f = os.fdopen(fd, 'w') f.write('abc') fd = get_some_fd() some_func(fd) some_other_func(fd)
Here’s what goes wrong: when some_func comes to an end, f (which is a file-like objects) goes out of scope, is destructed, which causes fd to be closed. I think this is pretty weird behavior (an object closing an fd it didn’t open itself), but well.
Here’s a better version, for reference:
def some_func(fd): f = os.fdopen(os.dup(fd), 'w') #Use f here