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

5

2 Answers

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.

3

"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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy