title: Most pythonic way to get output from a shell command
body: <p>I'm writing my first python program and I want to run a shell command and get the output. I want to do it in the cleanest possible / most pythonic way. This is what I've got atm.
  Note: I also want to raise an Exception when there went something worng with execution of the shell command.</p>
  
  <pre><code>def lsCommand():
      process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      out , err = process.communicate()
      returnc = process.returncode
      if returnc != 0:
          raise Exception(err)
      else:
          return out
  </code></pre>
  
  <p>What I discovered, is that when I remove the line <strong>out , err = process.communicate()</strong>, and replace it with time.sleep(4) (&lt;= the ls command doesn't take 4 seconds to complete), The returncode is None, which means that it the subprocess isn't fnished yet. How is this possible? Does the <strong>out , err = process.communicate()</strong> do an implicit wait() methode call?</p>
  
  <pre><code>def lsCommand():
      process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      time.sleep(4)
      returnc = process.returncode
      if returnc != 0:
          print returnc
          raise Exception(err)
      else:
          return out
  </code></pre>
  
  <p>EDIT: I'm using python 2.7</p>
  
  <p>I want to do a longer command <strong>sudo find  "/media/usb0"  -type f -name "*.JPG" | wc -l</strong>, but i'm not sure how to call it with Popen, can anyone help?</p>