Python error: subprocess.CalledProcessError: Command returned non-zero exit status 1

Python error: subprocess.CalledProcessError: Command returned non-zero exit status 1

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

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

#!/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

您正在 运行 执行的 grep 命令如果不匹配任何内容,将以退出状态 1 退出。该非零退出代码导致 check_output 引发异常(这就是其名称的 "check" 部分的含义)。

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

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

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

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

此外,写作 if data: would be betterif data is True:.

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

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