title: How to save an error message from subprocess command to file
body: <p>When running bash command using subprocess, I might run into situation where the command is not valid. In this case, bash would return an error messsage. How can we catch this message? I would like to save this message to a log file.
  The following is an example, where I try to list files in a non-existed directory.</p>
  <pre class="lang-py prettyprint-override"><code>try:
      subprocess.check_call([&quot;ls&quot;, &quot;/home/non&quot;]) 
      df = subprocess.Popen([&quot;ls&quot;, &quot;/home/non&quot;], stdout=subprocess.PIPE)        
      output, err = df.communicate()
      # process outputs
  except Exception as error:        
      print error
      sys.exit(1)
  </code></pre>
  <p>Bash would prints &quot;ls: cannot access /home/non: No such file or directory&quot;. How can I get this error message? The error caught by the except line is clearly different, it says &quot;Command '['ls', '/home/non']' returned non-zero exit status 2&quot;.</p>