Python 当子进程引发 CalledProcessError 异常时检查命令的返回码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15316398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check a command's return code when subprocess raises a CalledProcessError exception
提问by michaelmeyer
I want to capture the stdoutstream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command if it returns an error (that is, if its return code is not 0).
我想stdout在python(3)脚本中捕获shell命令的流,同时能够检查shell命令的返回码是否返回错误(即,如果它的返回码是不是 0)。
subprocess.check_outputseems to be the appropriate method to do this. From subprocess's man page:
subprocess.check_output似乎是执行此操作的适当方法。从subprocess的手册页:
check_output(*popenargs, **kwargs)
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
Still, I don't succeed to obtain the return code from the shell command when it fails. My code looks like this:
尽管如此,当它失败时,我没有成功从 shell 命令获取返回码。我的代码如下所示:
import subprocess
failing_command=['ls', 'non_existent_dir']
try:
subprocess.check_output(failing_command)
except:
ret = subprocess.CalledProcessError.returncode # <- this seems to be wrong
if ret in (1, 2):
print("the command failed")
elif ret in (3, 4, 5):
print("the command failed very much")
This code raises an exception in the handling of the exception itself:
此代码在处理异常本身时引发异常:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: type object 'CalledProcessError' has no attribute 'returncode'
I admit I don't know where I am wrong.
我承认我不知道我错在哪里。
采纳答案by jfs
To get both the process output and the returned code:
获取进程输出和返回的代码:
from subprocess import Popen, PIPE
p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)
subprocess.CalledProcessErroris a class. To access returncodeuse the exception instance:
subprocess.CalledProcessError是一个类。要访问returncode使用异常实例:
from subprocess import CalledProcessError, check_output
try:
output = check_output(["ls", "non existent"])
returncode = 0
except CalledProcessError as e:
output = e.output
returncode = e.returncode
print(returncode)
回答by Nodari Lipartiya
Most likely my answer is no longer relevant, but I think it may be solved with this code:
很可能我的答案不再相关,但我认为可以通过以下代码解决:
import subprocess
failing_command='ls non_existent_dir'
try:
subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
ret = e.returncode
if ret in (1, 2):
print("the command failed")
elif ret in (3, 4, 5):
print("the command failed very much")

