How to run an EXE, with argument, capture output value

Tim Harig usernet at ilthio.net
Thu Nov 18 17:22:35 EST 2010


On 2010-11-18, noydb <jenn.duerr at gmail.com> wrote:
> import subprocess
> pig = subprocess.Popen(["C:\Halls\hallbig2.exe"],
> stdin=subprocess.PIPE, stdout=subprocess.PIPE)
> result = pig.communicate(input='C:\Halls\Input\Ea39j.txt')[-1] #I need
> to capture the, what I think is the, last output

>From the subprocess documentation:

           [62]communicate() returns a tuple (stdoutdata, stderrdata).
           Note that if you want to send data to the process's stdin,
           you need to create the Popen object with stdin=PIPE. Similarly,
           to get anything other than None in the result tuple, you need
           to give stdout=PIPE and/or stderr=PIPE too.

By using index [-1] you are accessing the processes stderr stream.  I am
not really sure why you changed it.  It doesn't give you the last output.
Index 0 gives you *all* of stdout and index 1 gives you *all* of stderr,
period.  If you wish to further disect the output to get say the last line,
then you will need to parse it separately.

> print result
> print pig.returncode
>>> None
>>> 0
>
> So the tuple is empty. ??  The exe executes fine and returns output in
> th exe tool itself.  The python script seems to execute fine, no
> errors, '...returned exit code 0'.  Any ideas/suggestions?

No the tuple contains two items (stdout, stderr).  The first is what the
program printed to its stdout stream (which is most likely the output you
see if you run the command at a terminal/console).  The second is what it printed to its
stderr stream which is a channel used for out of band data such as error or
status messages.  In this case, it is None, because you did open stderr as a
subprocess.PIPE.



More information about the Python-list mailing list