Need feedback on subprocess-using function

gb345 gb345 at
Sat Oct 3 15:21:00 CEST 2009

I'm relatively new to Python, and I'm trying to get the hang of
using Python's subprocess module.  As an exercise, I wrote the Tac
class below, which can prints output to a file "in reverse order",
by piping it through the Unix tac utility.  (The idea is to delegate
the problem of managing the memory for an arbitrarily large task
to tac.)

class Tac(object):
    def __init__(self, path):
        out = open(path, 'w')
        self.pipe = subprocess.Popen(['tac'], stdout=out,
    def prn(self, string):
            self.pipe.stdin.write('%s\n' % string)

    def close(self):
        p = self.pipe
        err =
        if err:
            raise OSError(err)

This works OK, as far as I can tell, but I'm not sure that I've
dotted all the i's and crossed all the t's...  E.g., I had to add
the line "p.stdin.close()" to the close method when I when I ran
into sporadic deadlock at the statement.  Are there
other similar problems lurking in this code?  Also, there's no
robust mechanism for invoking this close method in case of an
exception (unless the exception happens during the execution of

Any comments and suggestions would be greatly appreciated.


More information about the Python-list mailing list