streaming Popen.stdout

Michele Simionato michele.simionato at gmail.com
Thu Feb 23 03:32:56 EST 2006


Replying to myself ...

I cooked up this solution involving os.pipe and os.fork, but I am not
especially happy with
it; anyway, let me write it. Feedback is welcome, since this was
written very quickly and
I may have missed something. BTW, are there libraries out there doing
something similar?

----

import subprocess
import os, sys, time

class ReadObject(object):
    def __init__(self, fileno):
        self.fileno = fileno
        self._closed = False
        self.name = str(self)
    def readline(self):
        if self._closed : return ''
        return ''.join(iter(self.read1, '\n')) + '\n'
    def read(self):
        return ''.join(iter(self.read1, '\x00'))
    def read1(self):
        c = os.read(self.fileno, 1)
        if c == '\x00':
            self._closed = True
            return '\n'
        else:
            return c
    def __iter__(self):
        return iter(self.readline, '')

class WriteObject(object):
    def __init__(self, fileno):
        self.fileno = fileno
        self.name = str(self)
    def write(self, text):
        os.write(self.fileno, text)
    def flush(self):
        pass
    def close(self):
        self.write('\x00')

def callproc(child, *args,**kw):
    "Run the child procedure in a child process"
    r, w = os.pipe()
    R, W = ReadObject(r), WriteObject(w)
    if os.fork(): # parent
        return R
    else: # child
        sys.stdout = W
        try:
            child(*args, **kw)
        finally:
            W.close()
        sys.exit()

if __name__ == '__main__':
    for line in callproc(subprocess.call, [sys.executable,
'hello.py']):
        print line,




More information about the Python-list mailing list