[Python-Dev] Avoiding file descriptors leakage in subprocess.Popen()

Christian Heimes lists at cheimes.de
Sat Jun 13 02:06:13 CEST 2009


Facundo Batista wrote:
> I just don't like a huge try/finally... but as FDs are just ints, do
> you think is there a better way to handle it?

How about a nice 'n shiny context wrapper for the pipe:


import os

class Pipe(object):
    def __enter__(self):
        self.read, self.write = os.pipe()
        return self.read, self.write

    def __exit__(self, *args):
        try:
            os.close(self.read)
        finally:
            # make sure that write is closed even if
            # self.read can't be closed
            os.close(self.write)


with Pipe() as (read, write):
    print read, write

Christian

PS and nit pick:
File descriptor are opaque resource handlers which just happened to be
ints. They should be treated as magic cookies.



More information about the Python-Dev mailing list