storing output of a command in a variable

822 views Asked by At

I have a python fabric file fabfile.py. I wish to store the result of a local command in a variable so that I can test it for various cases. For example I want to do this...

substring = "up-to-date"  
msg = local("git pull")
if msg.find(substring) == -1:
   "some action"

but I am not able to store the output in "msg variable". How can I do this ?

3

There are 3 answers

3
Chris Charles On

The way I've done this before is:

import subprocess

p = subprocess.Popen(['git', 'pull'], stdout=subprocess.PIPE, 
                                      stderr=subprocess.PIPE)
out, err = p.communicate()

if "up-to-date" in out:
   "some action"
1
uelei On

If you are using a version of Python older than 2.6 you can use popen, like in the example below.

import os
substring = "up-to-date"
msg = os.popen("git pull").read()
if msg.find(substring) == -1 :
   print "do something"
0
Ankit Sahu On

I've found the solution and it is pretty simple. We just need to pass another parameter capture=true with local to store the output of a command in a variable.

substring = "up-to-date"
msg = local("git pull", capture=true)
if substring in msg:
  "do something"
else:
  "do something else"