您可能会输出错误但返回码仍然为零。在您的代码中,您只捕获标准输出而不是标准错误。在下面的run函数中会运行一条命令,等待执行结束,然后读取returncode标准错误和标准输出。如果标准错误中有任何内容或返回码不为零,那么它将视为失败。您可以在代码中看到四个示例调用。第一个是正常的成功调用,第二个返回代码为 0,但有错误输出和标准输出。第三个有一个非零返回码和错误输出,而最后一个例子有一个非零返回码,根本没有输出。
代码
from subprocess import Popen, PIPE
def run(cmd):
print '-'*40
print 'running:', cmd
p = Popen(cmd, stderr=PIPE, stdout=PIPE, shell=True)
output, errors = p.communicate()
print [p.returncode, errors, output]
if p.returncode or errors:
print 'something went wrong...'
run("echo all is well")
run("echo out;echo error 1>&2")
run("this-will-fail")
run("exit 1")
输出
----------------------------------------
running: echo all is well
[0, '', 'all is well\n']
----------------------------------------
running: echo out;echo error 1>&2
[0, 'error\n', 'out\n']
something went wrong...
----------------------------------------
running: this-will-fail
[127, '/bin/sh: this-will-fail: not found\n', '']
something went wrong...
----------------------------------------
running: exit 1
[1, '', '']
something went wrong...