Reputation: 193
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 ?
Upvotes: 3
Views: 837
Reputation: 193
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"
Upvotes: 1
Reputation: 36
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"
Upvotes: 0
Reputation: 4446
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"
Upvotes: 5