[ACCEPTED]-How to redirect the output of .exe to a file in python?-io

Accepted answer
Score: 28

You can redirect directly to a file using 1 subprocess.

import subprocess
with open('output.txt', 'w') as output_f:
    p = subprocess.Popen('Text/to/execute with-arg',
Score: 10

Easiest is os.system("the.exe -a >thefile.txt"), but there are many other ways, for 2 example with the subprocess module in the standard 1 library.

Score: 3

You can do something like this e.g. to read 5 output of ls -l (or any other command)

p = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE)
print p.stdout.read() # or put it in a file

you 4 can do similar thing for stderr/stdin

but 3 as Alex mentioned if you just want it in 2 a file, just redirect the cmd output to 1 a file

Score: 0

If you just want to run the executable and 15 wait for the results, Anurag's solution 14 is probably the best. I needed to respond 13 to each line of output as it arrived, and 12 found the following worked:

1) Create an 11 object with a write(text) method. Redirect 10 stdout to it (sys.stdout = obj). In your 9 write method, deal with the output as it 8 arrives.

2) Run a method in a seperate thread 7 with something like the following code:

    p = subprocess.Popen('Text/to/execute with-arg', stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE, shell=False)
    while p.poll() is None:
        print p.stdout.readline().strip()

Because 6 you've redirected stdout, PIPE will send 5 the output to your write method line by 4 line. If you're not certain you're going 3 to get line breaks, read(amount) works too, I 2 believe.

3) Remember to redirect stdout back 1 to the default: sys.stdout = __sys.stdout__

Score: 0

Although the title (.exe) sounds like it's 12 a problem on Windows. I had to share that 11 the accepted answer (subprocess.Popen() with 10 stdout/stderr arguments) didn't work for 9 me on Mac OS X (10.8) with python 2.7.

I 8 had to use subprocess.check_output() (python 7 2.7 and above) to make it work. Example:

import subprocess

cmd = 'ls -l'
out = subprocess.check_output(cmd, shell=True)
with open('my.log', 'w') as f:

Note 6 that this solution writes all the accumulated 5 output out when the program finishes. If 4 you want to monitor the log file during 3 the run. You may want to try something else. In 2 my own case, I only cared about the end 1 result.

More Related questions