Capture output from subprocess.call that I have no control over
Question: I'm testing a piece of Python code that uses subprocess.call(), so I have no
control over that function call. I need to capture the output from that system
call to do assertions. I tried to set os.stdout to a StringIO object, but that
doesn't capture the system call outputs. How do I solve this problem? Here's
my code so far:

Code to test (I have no control over this):

    
    
    def runFile(filename):
        check_call("./" + filename)
    

My attempt to capture system call output:

    
    
    import StringIO
    oldout = sys.stdout
    try:
        sys.stdout = StringIO.StringIO()
        runFile("somefile")
        output = sys.stdout.getvalue()
        assert output == "expected-output"
    finally:
        sys.stdout = oldout
    


Answer: You could redirect your own stdout by

    
    
    rd, wr = os.pipe()
    oldstdout = os.dup(1)
    os.dup2(wr, 1)
    os.close(wr)
    

and then read from `rd` while the external process is running.

This might not work, as the external process might write more than fits in the
pipe buffer. In this case, you would have to spawn a reading thread.

Afterwards, you restore the old state with

    
    
    os.dup2(oldstdout, 1)
    os.close(oldstdout)
    os.close(rd)
    

and continue normally.

