Redirect screen output to text file
Question: My python script calls an executable (binary compiled from C++) like this:

    
    
    subprocess.call(["./rti", '1', '0.05', fileForRTI])
    

where `rti` executable name, `1`, `0.05` and `fileForRTI` are arguments.

This executable generates output to the console, but I want to output it to
the text file as well. What I tried is this (according to
[this](http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-
in-python)):

    
    
    import sys
    
    someFile = 'testFile'
    sys.stdout = open(someFile, "w")
    print(str(subprocess.call(["./rti", '1', '0.05', fileForRTI])))
    

But for some reason what is written to the file is just '1', while output is
much bigger.

I also tried this:

    
    
    p = Popen(['./rti', '1', '0.05', fileForRTI], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    output, err = p.communicate(b"input data that is passed to subprocess' stdin")
    rc = p.returncode
    print(rc)
    

But it's once again shows 1.

EDIT: also Kasra's solution give output 1 instead of what I see normally on
the screen.

Not sure if allowed, but a side question, if that `./rti` executable takes
long time to generate code, so is it possible to stop terminate and output to
file what is already seen on the screen.


Answer: You can use `subprocess.check_output()` :

    
    
    import subprocess
    try:
        out_bytes = subprocess.check_output(["./rti", '1', '0.05', fileForRTI])
    except subprocess.CalledProcessError as e:
        out_bytes = e.output # Output generated before error
        code= e.returncode # Return code
    

This runs the specified command and returns its output as a byte string. If
you need to interpret the resulting bytes as text, add a further decoding
step. For example:

    
    
    out_text = out_bytes.decode('utf-8')
    

The `check_output()` function is the easiest way to execute an external
command and get its output. However, if you need to perform more advanced
communication with a subprocess, such as sending it input, you’ll need to take
a difference approach. For that,use the `subprocess.Popen` class directly

