Python 子进程 check_output 返回非零退出状态 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27920837/
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
Subprocess check_output returned non-zero exit status 1
提问by Zongze Wu
This is my python code:
这是我的python代码:
import subprocess
subprocess.check_output("ls",shell=True,stderr=subprocess.STDOUT)
import subprocess
subprocess.check_output("yum",shell=True,stderr=subprocess.STDOUT)
The first .check_output()works well, but the second returns this:
第一个.check_output()效果很好,但第二个返回:
Traceback (most recent call last):
File "/usr/lib/x86_64-linux-gnu/gedit/plugins/pythonconsole/console.py", line 378, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
File "/usr/lib/python3.4/subprocess.py", line 616, in check_output
raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command 'yum' returned non-zero exit status 1
Why does this happen? Is it because lsis the original shell command but yumis the new package? How can I solve this problem?
为什么会发生这种情况?是不是因为ls原来的shell命令yum是新的包?我怎么解决这个问题?
采纳答案by Plouff
The command yumthat you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yumcommand to fix that.
yum您启动的命令已正确执行。它返回一个非零状态,这意味着在处理命令期间发生了错误。您可能想在yum命令中添加一些参数来解决这个问题。
Your code could show this error this way:
您的代码可能会以这种方式显示此错误:
import subprocess
try:
subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
回答by jfs
The word check_in the name means that if the command (the shell in this case that returns the exit status of the last command (yumin this case)) returns non-zero status then it raises CalledProcessErrorexception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_methods. You could use subprocess.callin your case because you are ignoring the captured output, e.g.:
check_名称中的单词意味着如果命令(在这种情况下,shell 返回最后一个命令的退出状态(yum在这种情况下))返回非零状态,那么它会引发CalledProcessError异常。这是设计使然。如果您要运行的命令在成功时可能返回非零状态,则要么捕获此异常,要么不使用check_方法。您可以subprocess.call在您的情况下使用,因为您忽略了捕获的输出,例如:
import subprocess
rc = subprocess.call(['grep', 'pattern', 'file'],
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
...
elif rc == 1: # not found
...
elif rc > 1: # error
...
You don't need shell=Trueto run the commands from your question.
您不需要shell=True运行问题中的命令。

