Python subprocess.check_output 返回码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23420990/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:57:54  来源:igfitidea点击:

subprocess.check_output return code

pythonsubprocess

提问by Juicy

I am using:

我在用:

grepOut = subprocess.check_output("grep " + search + " tmp", shell=True)

To run a terminal command, I know that I can use a try/except to catch the error but how can I get the value of the error code?

要运行终端命令,我知道我可以使用 try/except 来捕获错误,但是如何获取错误代码的值?

I found this on the official documentation:

我在官方文档中找到了这个:

 exception subprocess.CalledProcessError

    Exception raised when a process run by check_call() or check_output() returns a non-zero exit status.

    returncode

        Exit status of the child process.

But there are no examples given and Google was of no help.

但是没有给出例子,谷歌也没有帮助。

采纳答案by DanGar

You can get the error code and results from the exception that is raised.

您可以从引发的异常中获取错误代码和结果。

This can be done through the fields returncodeand output.

这可以通过字段returncode和来完成output

For example:

例如:

import subprocess

try:
   grepOut = subprocess.check_output("grep " + "test" + " tmp", shell=True)                       
except subprocess.CalledProcessError as grepexc:                                                                                                   
    print "error code", grepexc.returncode, grepexc.output

回答by jfs

is there a way to get a return code without a try/except?

有没有办法在没有 try/except 的情况下获得返回码?

check_outputraises an exception if it receives non-zero exit status because it frequently means that a command failed. grepmay return non-zero exit status even if there is no error -- you could use .communicate()in this case:

check_output如果它收到非零退出状态,则会引发异常,因为这通常意味着命令失败。grep即使没有错误,也可能返回非零退出状态——你可以.communicate()在这种情况下使用:

from subprocess import Popen, PIPE

pattern, filename = 'test', 'tmp'
p = Popen(['grep', pattern, filename], stdin=PIPE, stdout=PIPE, stderr=PIPE,
          bufsize=-1)
output, error = p.communicate()
if p.returncode == 0:
   print('%r is found in %s: %r' % (pattern, filename, output))
elif p.returncode == 1:
   print('%r is NOT found in %s: %r' % (pattern, filename, output))
else:
   assert p.returncode > 1
   print('error occurred: %r' % (error,))

You don't need to call an external command to filter lines, you could do it in pure Python:

您不需要调用外部命令来过滤行,您可以在纯 Python 中进行:

with open('tmp') as file:
    for line in file:
        if 'test' in line:
            print line,

If you don't need the output; you could use subprocess.call():

如果你不需要输出;你可以使用subprocess.call()

import os
from subprocess import call
try:
    from subprocess import DEVNULL # Python 3
except ImportError: # Python 2
    DEVNULL = open(os.devnull, 'r+b', 0)

returncode = call(['grep', 'test', 'tmp'], 
                  stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)

回答by mkobit

Python 3.5 introduced the subprocess.run()method. The signature looks like:

Python 3.5 引入了该subprocess.run()方法。签名看起来像:

subprocess.run(
  args, 
  *, 
  stdin=None, 
  input=None, 
  stdout=None, 
  stderr=None, 
  shell=False, 
  timeout=None, 
  check=False
)

The returned result is a subprocess.CompletedProcess. In 3.5, you can access the args, returncode, stdout, and stderrfrom the executed process.

返回的结果是一个subprocess.CompletedProcess。在3.5中,你可以访问argsreturncodestdout,并stderr从执行过程。

Example:

例子:

>>> result = subprocess.run(['ls', '/tmp'], stdout=subprocess.DEVNULL)
>>> result.returncode
0

>>> result = subprocess.run(['ls', '/nonexistent'], stderr=subprocess.DEVNULL)
>>> result.returncode
2

回答by simfinite

To get both output and return code (without try/except) simply use subprocess.getstatusoutput(Python 3 required)

要同时获取输出和返回代码(不带 try/except),只需使用subprocess.getstatusoutput(需要 Python 3)

回答by Noam Manos

In Python 2 - use commandsmodule:

在 Python 2 中 - 使用命令模块:

import command
rc, out = commands.getstatusoutput("ls missing-file")
if rc != 0: print "Error occurred: %s" % out

In Python 3 - use subprocessmodule:

在 Python 3 中 - 使用subprocess模块:

import subprocess
rc, out = subprocess.getstatusoutput("ls missing-file")
if rc != 0: print ("Error occurred:", out)

Error occurred: ls: cannot access missing-file: No such file or directory

发生错误:ls:无法访问丢失的文件:没有这样的文件或目录