Save command output to variable

I have a python fabfile.py file. I want to store the result of a local command in a variable so that I can test it for different 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 cannot save the output to the msg variable. How can i do this?

+3


source to share


3 answers


I've done this before:



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"

      

+5


source


I found a solution and it's pretty simple. We just need to pass another parameter capture=true

using local

to store the command output in a variable.



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

      

+1


source


If you are using a version of Python older than 2.6, you can use popen as 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


source







All Articles