【问题标题】:Check a command's return code when subprocess raises a CalledProcessError exception当子进程引发 CalledProcessError 异常时检查命令的返回码
【发布时间】:2013-02-25 07:40:38
【问题描述】:

我想在python(3)脚本中捕获shell命令的stdout流,同时能够检查shell命令的返回码是否返回错误(即, 如果它的返回码不是 0)。

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.

但是,当它失败时,我没有成功从 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")

这段代码在处理异常时引发了异常:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: type object 'CalledProcessError' has no attribute 'returncode'

我承认我不知道我错在哪里。

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    获取进程输出和返回代码:

    from subprocess import Popen, PIPE
    
    p = Popen(["ls", "non existent"], stdout=PIPE)
    output = p.communicate()[0]
    print(p.returncode)
    

    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)
    

    【讨论】:

      【解决方案2】:

      很可能我的答案不再相关,但我认为可以使用以下代码解决:

      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")
      

      【讨论】:

        猜你喜欢
        • 2016-09-22
        • 1970-01-01
        • 2021-10-24
        • 2018-12-09
        • 2015-05-16
        • 1970-01-01
        • 2019-09-19
        • 2021-10-07
        • 1970-01-01
        相关资源
        最近更新 更多