title: Check a command's return code when subprocess raises a CalledProcessError exception
body: <p>I want to capture the <code>stdout</code> stream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command if it returns an error (that is, if its return code is not 0).</p>
  
  <p><code>subprocess.check_output</code> seems to be the appropriate method to do this. From <code>subprocess</code>'s man page:</p>
  
  <pre><code>check_output(*popenargs, **kwargs)
      Run command with arguments and return its output as a byte string.
  
      If the exit code was non-zero it raises a CalledProcessError.  The
      CalledProcessError object will have the return code in the returncode
      attribute and output in the output attribute.
  </code></pre>
  
  <p>Still, I don't succeed to obtain the return code from the shell command when it fails. My code looks like this:</p>
  
  <pre><code>import subprocess
  failing_command=['ls', 'non_existent_dir']
  
  try:
      subprocess.check_output(failing_command)
  except:
      ret = subprocess.CalledProcessError.returncode  # &lt;- this seems to be wrong
      if ret in (1, 2):
          print("the command failed")
      elif ret in (3, 4, 5):
          print("the command failed very much")
  </code></pre>
  
  <p>This code raises an exception in the handling of the exception itself:</p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;stdin&gt;", line 4, in &lt;module&gt;
  AttributeError: type object 'CalledProcessError' has no attribute 'returncode'
  </code></pre>
  
  <p>I admit I don't know where I am wrong.</p>