How to redirect stdout to screen and at the same time save to a variable
<p>I am trying to redirect stdout to screen and at the same time save to a variable and running into error <code>AttributeError: __exit__</code> at line <code>with proc.stdout:</code>,can anyone tell me how to accomplish this?</p>

<pre><code>...............
proc = subprocess.Popen(cmd.split(' '), stderr=subprocess.PIPE)
try:
    proc.wait(timeout=time_out) 
except TimeoutExpired as e:
    print e
    proc.kill()
with proc.stdout:
    for line in proc.stdout:
        print line
</code></pre>

<p>Error:-</p>

<pre><code>    with proc.stdout:
AttributeError: __exit__
</code></pre>

<p><strong>UPDATE:-</strong></p>

<pre><code>proc = subprocess.Popen(cmd.split(' '),stdout=subprocess.PIPE )
print "Executing %s"%cmd
try:
    proc.wait(timeout=time_out)//HUNG here until timeout kicks-in
except TimeoutExpired as e:
    print e
    proc.kill()
with proc.stdout as stdout:
    for line in stdout:
        print line,
</code></pre>

<p>When creating your Popen object you have the stderr set. When you go to open the stdout subprocess can't open it because you have stderr set instead. You can fix this by either adding <code>stdout=subprocess.PIPE</code> to the Popen object args, or by doing <code>with proc.stderr</code> instead of <code>with proc.stderr</code>. Also, you want to change your with statement a little, like this.</p>

<pre><code>with proc.stdout as stdout:
    for line in stdout:
        sys.stdout.write(line)
</code></pre>

python