Storing Subprocess Results

topazcode ter at topazcode.com
Tue Sep 2 20:48:23 EDT 2008


On Sep 2, 6:31 pm, Karthik Gurusamy <kar1... at gmail.com> wrote:
> On Sep 2, 7:16 am, topazcode <t... at topazcode.com> wrote:
>
> > I am using the subprocess module to run some shell commands on a Linux
> > system:
>
> > import subprocess
> > output = subprocess.call('''ssh server1 "uptime"''', shell=True)
>
> > The above assigns the output variable with a return code, i.e. 0 in
> > this case.  How can I actually capture the data returned from
> > subprocess.call, rather than just the return code?  I'd like to have
> > the output variable contain the uptime string in this case.
>
> Probably commands module is a better choice for your problem:>>> import commands
> >>> commands.getoutput('fortune')
>
> "While money can't buy happiness, it certainly lets you choose your own
> \nform of misery."
>
>
>
> Karthik
>
>  Any help
>
> > is appreciated.  Thanks.

Thanks guys.  I went ahead and used subprocess.Popen as suggested and
that works fine.  Did something like:

import subprocess
subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout_value, stderr_value = subprocess.communicate()

The above worked great.  The 'uptime' was actually a fairly long
stretch of commands, and this allows me to check for STDERR and act
accordingly.  Thanks again for the help and suggestions.



More information about the Python-list mailing list