Get only stderr output from subprocess.check_output
<p>I want to run an external process in python, and process its <code>stderr</code> only.</p>

<p>I know I can use <code>subprocess.check_output</code>, but how can I redirect the stdout to <code>/dev/null</code> (or ignore it in any other way), and receive only the <code>stderr</code>?</p>

<p>Unfortunately you have tagged this <a href="/questions/tagged/python-2.7" class="post-tag" title="show questions tagged &#39;python-2.7&#39;" rel="tag">python-2.7</a>, as in python 3.5 and up this would be simple using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow"><code>run()</code></a>:</p>

<pre><code>import subprocess

output = subprocess.run(..., stdout=subprocess.DEVNULL,
                        stderr=subprocess.PIPE).stderr
</code></pre>

<p>With <code>check_output()</code> stdout simply cannot be redirected:</p>

<pre><code>&gt;&gt;&gt; subprocess.check_output(('ls', 'asdfqwer'), stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
    raise ValueError('stdout argument not allowed, it will be overridden.')
ValueError: stdout argument not allowed, it will be overridden.
</code></pre>

<p>Use <a href="https://docs.python.org/2/library/subprocess.html#popen-objects" rel="nofollow"><code>Popen</code></a> objects and <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>communicate()</code></a> with python versions less than 3.5. Open <code>/dev/null</code> using <a href="https://docs.python.org/2/library/os.html#os.devnull" rel="nofollow"><code>os.devnull</code></a> in python 2.7:</p>

<pre><code>&gt;&gt;&gt; import subprocess
&gt;&gt;&gt; import os
&gt;&gt;&gt; with open(os.devnull, 'wb') as devnull:
...     proc = subprocess.Popen(('ls', 'asdfqwer'),
...                             stdout=devnull,
...                             stderr=subprocess.PIPE)
...     proc.communicate()
...     proc.returncode
... 
(None, "ls: cannot access 'asdfqwer': No such file or directory\n")
2
</code></pre>

<p>Communicate sends input to stdin, if piped, and reads from stdout and stderr until end-of-file is reached.</p>

python python-2.7 subprocess stderr