4

I need to count the lines of a shell-command output in python script.

This function works fine in case there is output, but in case the output is empty, it gives an error as explained in the error output.
I tried to avoid that using an if statement in case the output of the command is None, but that didn't help.

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

Error output:

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
Anmol Singh Jaggi
  • 8,376
  • 4
  • 36
  • 77
Adam
  • 159
  • 2
  • 5
  • 12

3 Answers3

6

The grep command you're running exits with exit status 1 if it doesn't match anything. That non-zero exit code causes check_output to raise an exception (that's what the "check" part of its name means).

If you don't want a failed match to raise an exception, consider using subprocess.getoutput instead of check_output. Or you could change your command to avoid non-zero exit codes:

func = "nova list | grep Shutdown || true"
Blckknght
  • 100,903
  • 11
  • 120
  • 169
1

That is how it worked As described in first solution : The grep command exits with exit status 1 if it doesn't match anything. That non-zero exit code causes check_output to raise an exception (that's what the "check" part of its name means).

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

The code :

  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
Adam
  • 159
  • 2
  • 5
  • 12
0

You can surround the subprocess invocation by a try-except block:

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

Also, writing if data: would be better than if data is True:.

Community
  • 1
  • 1
Anmol Singh Jaggi
  • 8,376
  • 4
  • 36
  • 77
  • both proposed solution worked fine . – Adam Mar 23 '16 at 19:51
  • That's great! Although you don't need both at the same time. In my opinion, @Blckknght's answer is better, since it avoids the use of exceptions, thus making the code faster (I'm the one who has upvoted it). I wrote my answer to just add another way of doing this. – Anmol Singh Jaggi Mar 23 '16 at 20:09