Skip to content

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')

fd = get_some_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

Try this on fd 0/1/2 in an (I)Python shell ;-)

Posted in Development.

Tagged with .

3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Josh Stone says

    The issue has nothing to do with Python per se — that’s the way fdopen() is defined in libc. The man-page directly says, “The file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed.”

    But yes, I can see how this might be a surprising effect…

  2. willem says

    Josh is right. This is normal behavior. You should make it a habit to dup() the file descriptor :)

  3. Eugene says

    I am looking for some idea and stumble upon your posting :) decide to wish you Thanks. Eugene

Some HTML is OK

or, reply to this post via trackback.