Reputation: 9795
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
Upvotes: 15
Views: 57105
Reputation: 23261
If the return code was non-zero it raises a
CalledProcessError
. TheCalledProcessError
object will have the return code in thereturncode
attribute and any output in theoutput
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.
Upvotes: 20
Reputation: 295954
"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.
Upvotes: 7