Subprocess not capturing the output of stdout storing it inside a variable in Python
<p>I tried the below code to capture the output from screen using the sub-process, but its not doing what I intended to do.</p>

<pre><code>#!/tools/bin/python

import subprocess

result = subprocess.check_output("echo $USERNAME", shell=True)
print result
</code></pre>

<p>expected output is:</p>

<pre><code>vimo 
vimo 
</code></pre>

<p>i.e. one for the echo process and one for printing the result output. 
But what I see is </p>

<pre><code>vimo
</code></pre>

<p>But when I try to print the result output, its always empty.</p>

<p>What am I missing in the above puzzle !! Help out !!</p>

<p>Here you goes some greatly stripped (and altered for privacy reasons) raw <em>dummy</em>  piece of code, grabbing both stdin and stdout from external script output.</p>

<pre><code>from subprocess import Popen, PIPE

cmd = ['echo', 'foo']

proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
comm = proc.communicate()

if proc.returncode != 0:
    # code to handle / parse stderr (comm[1])
    raise RuntimeError(
        '\'%s\': command has failed (%d):\n%s'
        % ('some value', proc.returncode, comm[1]))

for line in comm[0].split('\n'):
    if line.find('Wrote:') == 0:
        # some code to parse stdout
        pass
</code></pre>

python python-2.7