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

Christian Heimes lists at cheimes.de
Sat Jun 13 02:06:22 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):
            # make sure that write is closed even if
            # self.read can't be closed

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


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