views:

832

answers:

4

In a script , I want to run a .exe with some command line parameters as "-a",and then

redirect the standard output of the program to a file?

How can I implement that?

+4  A: 

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

Alex Martelli
how to use that subprocess?
Jinx
See http://docs.python.org/library/subprocess.html#replacing-os-system .
Alex Martelli
It's worth remembering the pipe symbol differs between operating systems when trying to use os.system to redirect things...
mavnn
+1  A: 

you can do something like this e.g. to read output of ls -l (same will work for cmd)

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

you can do similar thing for stderr/stdin

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

Anurag Uniyal
If it's a long running process, be aware that stdout.read() is blocking. You'll want to run the subprocess on a different thread if the script is going to continue doing anything else or respond to the output 'live'.
mavnn
A: 

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

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

2) Run a method in a seperate thread 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 you've redirected stdout, PIPE will send the output to your write method line by line. If you're not certain you're going to get line breaks, read(amount) works too, I believe.

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

mavnn
+4  A: 

You can redirect directly to a file using subprocess.

import subprocess
output_f = open('output.txt', 'w')
p = subprocess.Popen('Text/to/execute with-arg',
                     stdout=output_f,
                     stderr=output_f)
monkut