要添加到Paul的答案(使用subprocess.check_output):
我稍微重写了一下,以便更容易地处理可能抛出错误的命令(例如,在非g it目录中调用“git status”将抛出返回代码128和CalledProcessError)
下面是我的工作Python 2.7示例: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