Capture standard output for Python child spawned by external package
Question: I would like to capture in a file the standard output by a child Process
spawned by an external package.

I can NOT simply redirect sys.stdout to a file, as this does not capture the
output of new processes ([How can I capture the stdout output of a child
process?](http://stackoverflow.com/questions/923079/how-can-i-capture-the-
stdout-output-of-a-child-process)).

But unfortunately, I also can NOT simply use subprocess or the terminal to
capture stdout, since I am not spawning the process -- it is spawned by the
code in an external Python package.

Specifically, I am using the API to the package pystan. Some of the functions
in this package spawn child MCMC runs that write to standard output.


Answer: I only see two ways to do this:

  * monkey-patch `pystan` (might take several patches)
  * monkey-patch `subprocess` (might get more info than you want)

I would go with the `subprocess` monkey-patch: write your own version of
`Popen` (or whatever `pystan` is using, and replace the `subprocess` version
with your own. Your version would track `STDOUT` and save it somewhere you
could get at it.

Roughly, something like this:

    
    
    import subprocess
    original_Popen = subprocess.Popen
    
    def my_Popen(..., stdout=PIPE, ...):  # or somesuch
        ...
    
    subprocess.Popen = my_Popen
    
    # call pystan here
    
    subprocess.Popen = original_Popen # if needed 
    

