To add to Paul's answer (using subprocess.check_output):
I slightly rewrote it to work easier with commands that can throw errors (e.g. calling "git status" in a non-git directory will throw return code 128 and a CalledProcessError)
Here's my working Python 2.7 example:
import subprocess
class MyProcessHandler( object ):
# *********** constructor
def __init__( self ):
# return code saving
self.retcode = 0
# ************ modified copy of subprocess.check_output()
def check_output2( self, *popenargs, **kwargs ):
# open process and get returns, remember return code
pipe = subprocess.PIPE
process = subprocess.Popen( stdout = pipe, stderr = pipe, *popenargs, **kwargs )
output, unused_err = process.communicate( )
retcode = process.poll( )
self.retcode = retcode
# return standard output or error output
if retcode == 0:
return output
else:
return unused_err
# call it like this
my_call = "git status"
mph = MyProcessHandler( )
out = mph.check_output2( my_call )
print "process returned code", mph.retcode
print "output:"
print out