In Python subprocess, what is the difference between using Popen() and check_output()?
<p>Take the shell command "cat file.txt" as an example. </p>

<p>With Popen, this could be run with</p>

<pre><code>import subprocess
task = subprocess.Popen("cat file.txt", shell=True,  stdout=subprocess.PIPE)
data = task.stdout.read()
</code></pre>

<p>With check_output, one could run</p>

<pre><code>import subprocess
command=r"""cat file.log"""
output=subprocess.check_output(command, shell=True)
</code></pre>

<p>These appears to be equivalent. What is the difference with regards to how these two commands would be used? </p>

<p><code>Popen</code> is the class that defines an object used to interact with an external process. <code>check_output()</code> is just a wrapper around an instance of <code>Popen</code> to examine its standard output. Here's the definition from Python 2.7 (sans docstring):</p>

<pre><code>def check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output
</code></pre>

<p>(The definition is quite a bit different, but is still ultimately a wrapper around an instance of <code>Popen</code>.)</p>

python bash shell subprocess