To add to Paul's answer (using subprocess.check_output):
I rewrote it a bit to make it easier to work with commands that may cause errors (for example, calling "git status" in a non-git directory will trigger a 128 return code and CalledProcessError)
Here is 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
Simon source share