【问题标题】:Python error: subprocess.CalledProcessError: Command returned non-zero exit status 1 [duplicate]Python错误:subprocess.CalledProcessError:命令返回非零退出状态1 [重复]
【发布时间】:2016-07-11 05:50:21
【问题描述】:

我需要计算 Python 脚本中 shell 命令输出的行数。

这个函数在有输出的情况下可以正常工作,但如果输出为空,它会给出一个错误,如错误输出中所述。
如果命令的输出是None,我试图避免使用if 语句,但这没有帮助。

#!/usr/bin/python
import subprocess

lines_counter=0
func="nova list | grep Shutdown "
data=subprocess.check_output(func, shell=True)
if data is True:
       for line in data.splitlines():
               lines_counter +=1
print lines_counter

错误输出:

data=subprocess.check_output(func, shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'nova list | grep Shutdown ' returned non-zero exit status 1

【问题讨论】:

    标签: python command-line subprocess


    【解决方案1】:

    如果您正在运行的grep 命令与任何内容都不匹配,则会以退出状态1 退出。该非零退出代码导致check_output 引发异常(这就是其名称中“检查”部分的含义)。

    如果您不希望失败的匹配引发异常,请考虑使用subprocess.getoutput 而不是check_output。或者您可以更改命令以避免非零退出代码:

    func = "nova list | grep Shutdown || true"
    

    【讨论】:

    • 但是 subprocess.getoutput 似乎只存在于 python3 中。 (python2 文档中未提及)
    【解决方案2】:

    您可以用 try-except 块包围 subprocess 调用:

    try:
        data = subprocess.check_output(func, shell=True)
    except Exception:
        data = None
    

    另外,写if data:would be better而不是if data is True:

    【讨论】:

    • 两个建议的解决方案都很好。
    • 太棒了!尽管您不需要同时使用两者。在我看来,@Blckknght 的答案更好,因为它避免了使用异常,从而使代码更快(我是赞成它的人)。我写我的答案只是为了添加另一种方法。
    【解决方案3】:

    这就是它的工作原理 如第一个解决方案中所述: 如果不匹配任何内容,则 grep 命令以退出状态 1 退出。该非零退出代码导致 check_output 引发异常(这就是其名称的“检查”部分的含义)。

    func = "nova list | grep Shutdown || true"
    

    代码:

      lines_counter=0
        func="nova list | grep Shutdown || true"
        try:
            data = subprocess.check_output(func, shell=True)
        except Exception:
            data = None
        for line in data():
                lines_counter +=1
        print lines_counter
    

    【讨论】:

      猜你喜欢
      • 2014-01-13
      • 1970-01-01
      • 2016-01-01
      • 2016-08-09
      • 2021-02-15
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多