直接给大家上实现代码演示:
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
out, err = p.communicate()
print ('cmd=[{}] out=[{}] err=[{}] returncode=[{}]'.format(cmd, out, err, p.returncode))
if p.returncode != 0:
raise Exception('cmd run error')
return out通过上述的实现代码演示,我们可以直接调用run函数来运行命令,得到命令的标准输出,在返回码非0的情况下,直接抛出异常。