Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.CalledProcessError: what *is* the error?

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

like image 273
kev Avatar asked Dec 11 '22 14:12

kev


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

like image 93
Łukasz Rogalski Avatar answered Dec 20 '22 22:12

Łukasz Rogalski