4
votes
import subprocess

cmd = "grep -r * | grep jquery"
print cmd

subprocess.check_output(cmd, shell=True)

subprocess.CalledProcessError: Command 'grep -r * | grep jquery' returned non-zero exit status 1

I can execute that command in my shell without issues. How can I see the actual error in python?

The snippet is part of a larger script which takes multiple arguments and chains the grep commands + adds some excludes (I don't need to grep log files or minified JavaScript. Hence the pedantic syntax.

Python 2.7.10

2
That just means the command returned a non-zero exit code...which is exactly what grep does if your match fails. - larsks
aaah! no results you mean? - kev
Maybe there is something I'm misunderstanding with your grep command, but are you looking for jquery within a path? Why not just grep -r jquery .? - idjaw
BTW, grep -r * looks for the name of the first file in your directory inside all the other files in your directory. I can't conceive of under what circumstances that would be correct behavior. - Charles Duffy
thanks for clarifying! good that I asked :-) I've changed it to grep -r jquery . - kev

2 Answers

7
votes

Quoting docs:

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

import subprocess

cmd = "grep -r * | grep jquery"
print cmd

try:
    subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
    print e.returncode
    print e.output

Of error message was printed to stderr, you need keyword argument stderr=subprocess.STDOUT.

There is no other source of 'what went wrong' besides return code and stdout / stderr.

5
votes

"non-zero exit status" means that the command you ran indicated a status other than success. For grep, the documentation explicitly indicates that an exit status of 1 indicates no lines were found, whereas an exit status more than 1 indicates that some other error took place.

To quote the manual:

EXIT STATUS - The grep utility exits with one of the following values:

0     One or more lines were selected.
1     No lines were selected.
>1    An error occurred.

By the way -- if you want to look for the string jquery in all files under the current directory (recursively), use grep -r jquery .; grep -r * searches for the name of the first file in your directory inside the contents of all other files in your directory.